event_hub/reactive

The reactive module provides a way to manage and notify subscribers about events based on a state that can be dynamically retrieved. It supports creating observers that can react to changes in state, which can be useful for broadcasting things that constantly change like the current time or database updates.

Examples

Reactive Observer

import gleam/io
import event_hub/reactive

pub fn main() {
  let get_time = fn() { "2024-05-21T16:30:00Z" }

  use hub <- reactive.new(get_time)
  let unsubscribe =
    reactive.subscribe(hub, fn(value) { io.println("Current time: " <> value) })

  reactive.notify(hub)

  unsubscribe()
  reactive.notify(hub)
}

Types

Represents a hub for managing event subscriptions and notifications based on dynamic state.

pub opaque type Hub(value_type)

Represents a function that returns the current state value.

pub type State(value_type) =
  fn() -> value_type

Functions

pub fn new(
  with state: fn() -> a,
  in context: fn(Hub(a)) -> b,
) -> b

Creates a new reactive observer hub, executes the given context with the hub.

Parameters

  • state: A function that returns the current state value.
  • context: A function that takes the created Hub and returns a result.

Returns

The result of executing the context function.

Example

import event_hub/reactive

pub fn example() {
  let get_state = fn() { "current state" }

  reactive.new(get_state, fn(hub) {
    // Use the hub
    Nil
  })
}
pub fn notify(on hub: Hub(a)) -> a

Notifies subscribers of the hub about an event with the current state value. These notifications occur in parallel but notify waits for all of them to complete.

Parameters

  • hub: The Hub to notify.

Returns

The current state value.

Example

import event_hub/reactive

pub fn example(hub: reactive.Hub(String)) {
  let value = reactive.notify(hub)
}
pub fn subscribe(
  on hub: Hub(a),
  with callback: fn(a) -> Nil,
) -> fn() -> Nil

Subscribes to state changes and returns an unsubscribe function. The callback will be invoked with the current state value when notify is called.

Parameters

  • hub: The Hub to add the callback to.
  • callback: The callback function to invoke with the current state value.

Returns

An Unsubscribe function that can be called to remove the callback.

Example

import gleam/io
import event_hub/reactive

pub fn example(hub: reactive.Hub(String)) {
  let unsubscribe =
    reactive.subscribe(hub, fn(value) {
      io.println("Received state: " <> value)
    })

  // To unsubscribe
  unsubscribe()
}
Search Document