whisper

Types

pub type ReceiveError {
  TopicIsNotRegistered
  SubscriptionCancelled
}

Constructors

  • TopicIsNotRegistered
  • SubscriptionCancelled
pub type ReceiveResult(a) {
  Message(a)
  Empty
  Closed(ReceiveError)
}

Constructors

pub type Subscription(a) {
  Subscription(
    receive: fn() -> ReceiveResult(a),
    cancel: fn() -> Nil,
  )
}

Constructors

  • Subscription(
      receive: fn() -> ReceiveResult(a),
      cancel: fn() -> Nil,
    )
pub type TopicError {
  InvalidTopic
  InvalidCapacity
  AlreadyRegistered
}

Constructors

  • InvalidTopic
  • InvalidCapacity
  • AlreadyRegistered
pub type Whisper(a) {
  Whisper(topic: String, capacity: Int)
}

Constructors

  • Whisper(topic: String, capacity: Int)

Values

pub fn close(whisper: Whisper(a)) -> Nil

Closes the topic and notifies all active subscriptions.

After closing, subscribers will receive Closed(TopicIsNotRegistered) when attempting to receive messages, and new subscriptions or listeners cannot be created for this topic.

Examples

close(whisper)
pub fn new_topic(
  topic: String,
  capacity: Int,
) -> Result(Whisper(a), TopicError)

Creates a new topic with the specified capacity for message buffering.

The topic name must be non-empty and the capacity must be greater than zero. Returns an error if the topic name is invalid, capacity is invalid, or the topic is already registered.

Examples

let assert Ok(whisper) = new_topic("notifications", capacity: 100)
pub fn on(
  whisper: Whisper(a),
  listener: fn(a) -> Nil,
) -> fn() -> Nil

Registers a listener function that will be called whenever a message is published to the topic.

Returns a function that can be called to unregister the listener. Multiple listeners can be registered on the same topic, and each will receive all published messages.

Examples

let close = on(whisper, fn(message) {
  io.println("Received: " <> message)
})
// Later, to stop listening:
close()
pub fn publish(whisper: Whisper(a), message: a) -> Nil

Publishes a message to all listeners and subscribers of the topic.

The message will be queued for each subscription up to the topic’s capacity. If a subscription’s queue is full, older messages may be dropped depending on the platform implementation.

Examples

publish(whisper, "Hello, world!")
pub fn subscribe(whisper: Whisper(a)) -> Subscription(a)

Creates a subscription that allows pulling messages from the topic on demand.

Unlike on, which pushes messages to a callback, subscribe returns a Subscription that can be polled using its receive function. The subscription maintains its own message queue up to the topic’s capacity.

Call the subscription’s cancel function to stop receiving messages.

Examples

let sub = subscribe(whisper)
case sub.receive() {
  Message(msg) -> io.println("Got: " <> msg)
  Empty -> io.println("No messages")
  Closed(err) -> io.println("Subscription closed")
}
// Later, to cancel:
sub.cancel()
Search Document