event_hub
The event_hub
module provides a way to manage and notify subscribers about events.
It supports stateless observers, allowing functions to be registered and invoked in parallel when an event occurs.
Examples
Simple Observer
import gleam/io
import event_hub
pub fn main() {
use hub <- event_hub.new()
let unsubscribe =
event_hub.subscribe(hub, fn(value) {
io.println("Received value: " <> value)
})
event_hub.notify(hub, "Hello, world!")
unsubscribe()
event_hub.notify(hub, "This won't be received")
}
Types
Represents a callback function that gets called with a value when an event occurs.
pub type Callback(value_type) =
fn(value_type) -> Nil
Represents a hub for managing event subscriptions and notifications.
pub type Hub(value_type)
Represents an unsubscribe function that can be called to remove a previously added callback.
pub type Unsubscribe =
fn() -> Nil
Functions
pub fn new(in context: fn(Hub(a)) -> b) -> b
Creates a new stateless observer hub, executes the given context with the hub, and stops the hub afterward.
Parameters
context
: A function that takes the createdHub
and returns a result.
Returns
The result of executing the context function.
Example
import event_hub
pub fn example() {
event_hub.new(fn(hub) { event_hub.notify(hub, "event") })
}
pub fn notify(on hub: Hub(a), with value: a) -> Nil
Notifies all subscribers of the hub that an event has occurred with the given value.
These notifications occur in parallel but notify
waits for all of them to complete.
Parameters
hub
: TheHub
to notify.value
: The value to send to all subscribers.
Example
import event_hub
pub fn example(hub: event_hub.Hub(String)) {
event_hub.notify(hub, "event")
}
pub fn subscribe(
on hub: Hub(a),
with callback: fn(a) -> Nil,
) -> fn() -> Nil
Adds a callback to the hub and returns an unsubscribe function.
Parameters
hub
: TheHub
to add the callback to.callback
: The callback function to add.
Returns
An Unsubscribe
function that can be called to remove the callback.
Example
import gleam/io
import event_hub
pub fn example(hub: event_hub.Hub(String)) {
let unsubscribe =
event_hub.subscribe(hub, fn(value) {
io.println("Received value: " <> value)
})
// To unsubscribe
unsubscribe()
}