topics
PubSub — topic-based publish/subscribe for Gleam.
Processes subscribe to string topics and receive messages broadcast to them. Dead subscribers are pruned automatically on each subscribe and broadcast, so crashed processes never accumulate in the registry.
Usage
let assert Ok(ps) = topics.start()
let subject = process.new_subject()
topics.subscribe(ps, "events", subject)
topics.broadcast(ps, "events", "something happened")
let assert Ok(msg) = process.receive(subject, within: 1000)
// msg == "something happened"
topics.unsubscribe(ps, "events", subject)
Types
pub type PubSub(msg) =
process.Subject(PubSubMessage(msg))
pub opaque type PubSubMessage(msg)
Values
pub fn broadcast(
ps: process.Subject(PubSubMessage(msg)),
topic: String,
message: msg,
) -> Nil
Broadcast a message to all live subscribers of a topic.
pub fn list_topics(
ps: process.Subject(PubSubMessage(msg)),
) -> List(String)
List all topics that have at least one subscriber.
pub fn start() -> Result(
process.Subject(PubSubMessage(msg)),
actor.StartError,
)
Start a new PubSub instance.
pub fn start_linked() -> Result(
actor.Started(process.Subject(PubSubMessage(msg))),
actor.StartError,
)
Start a new PubSub instance, returning the full Started record for use
with supervision trees.
pub fn subscribe(
ps: process.Subject(PubSubMessage(msg)),
topic: String,
subscriber: process.Subject(msg),
) -> Nil
Subscribe to a topic. The subject receives every message broadcast to that topic. Idempotent — subscribing the same subject twice to the same topic is a no-op.
pub fn subscriber_count(
ps: process.Subject(PubSubMessage(msg)),
topic: String,
) -> Int
Return the number of live subscribers for a topic.
pub fn unsubscribe(
ps: process.Subject(PubSubMessage(msg)),
topic: String,
subscriber: process.Subject(msg),
) -> Result(Nil, String)
Unsubscribe from a topic.