effect-io-ai

Package: effect
Module: PubSub

PubSub.PubSub

A PubSub<A> is an asynchronous message hub into which publishers can publish messages of type A and subscribers can subscribe to take messages of type A.

Example (Publishing and subscribing to messages)

import { Effect, PubSub } from "effect"

const program = Effect.gen(function*() {
  // Create a bounded PubSub with capacity 10
  const pubsub = yield* PubSub.bounded<string>(10)

  // Subscribe and consume messages
  yield* Effect.scoped(Effect.gen(function*() {
    const subscription = yield* PubSub.subscribe(pubsub)

    // Publish messages
    yield* PubSub.publish(pubsub, "Hello")
    yield* PubSub.publish(pubsub, "World")

    const message1 = yield* PubSub.take(subscription)
    const message2 = yield* PubSub.take(subscription)
    console.log(message1, message2) // "Hello", "World"
  }))
})

Signature

export interface PubSub<in out A> extends Pipeable {
  readonly [TypeId]: {
    readonly _A: Invariant<A>
  }
  readonly pubsub: PubSub.Atomic<A>
  readonly subscribers: PubSub.Subscribers<A>
  readonly scope: Scope.Closeable
  readonly shutdownHook: Latch.Latch
  readonly shutdownFlag: MutableRef.MutableRef<boolean>
  readonly strategy: PubSub.Strategy<A>
}

Source

Since v2.0.0