PubSubx (pub_subx v0.1.2)
PubSubx
is a simple publish-subscribe (PubSub) system built on top of Elixir's GenServer
and Registry
.
The module allows processes to subscribe to topics, publish messages to those topics, and manage subscriptions. It efficiently handles message delivery to subscribed processes and automatically cleans up subscriptions when processes terminate.
Features
- Subscribe/Unsubscribe: Processes can subscribe or unsubscribe from topics.
- Publish: Messages can be published to a topic, and all subscribers to that topic will receive the message.
- Dynamic Topics: Topics are dynamically created as they are subscribed to, and they are removed when no subscribers exist.
- Process Monitoring: Automatically removes subscribers when the process is no longer alive.
Example Usage
Start the PubSubx server:
{:ok, pid} = PubSubx.start_link(name: :my_pubsub)
Subscribe a process to a topic:
PubSubx.subscribe(:my_topic, self(), :my_pubsub)
Publish a message to the topic:
PubSubx.publish(:my_topic, "Hello, subscribers!", :my_pubsub)
Get the list of subscribers:
subscribers = PubSubx.subscribers(:my_topic, :my_pubsub)
Unsubscribe a process from a topic:
PubSubx.unsubscribe(:my_topic, self(), :my_pubsub)
Summary
Functions
Returns a specification to start this module under a supervisor.
Publishes a message to the specified topic
.
Starts the PubSubx
server.
Subscribes a given process (pid
) to a specific topic
.
Returns a list of PIDs that are subscribed to the specified topic
.
Lists all topics that have active subscribers.
Unsubscribes a given process (pid
) from the specified topic
.
Types
process()
topic()
Functions
child_spec(init_arg)
Returns a specification to start this module under a supervisor.
See Supervisor
.
publish(topic, message, name \\ __MODULE__)
Publishes a message to the specified topic
.
All subscribers to that topic
will receive the message
.
If a name
is not provided, it defaults to the PubSubx
module name.
start_link(opts \\ [])
@spec start_link(Keyword.t()) :: GenServer.on_start()
Starts the PubSubx
server.
Options
subscribe(topic, pid, name \\ __MODULE__)
Subscribes a given process (pid
) to a specific topic
.
If a name
is not provided, it defaults to the PubSubx
module name.
subscribers(topic, name \\ __MODULE__)
Returns a list of PIDs that are subscribed to the specified topic
.
If a name
is not provided, it defaults to the PubSubx
module name.
topics(name \\ __MODULE__)
Lists all topics that have active subscribers.
If a name
is not provided, it defaults to the PubSubx
module name.
unsubscribe(topic, pid, name \\ __MODULE__)
Unsubscribes a given process (pid
) from the specified topic
.
If a name
is not provided, it defaults to the PubSubx
module name.