Hyperlinkv0.8.0-beta.28

PubSub

PubSub.subscribeconsteffect/PubSub.ts:1092
<A>(self: PubSub<A>): Effect.Effect<Subscription<A>, never, Scope.Scope>

Subscribes to receive messages from the PubSub. The resulting subscription can be evaluated multiple times within the scope to take a message from the PubSub each time.

Example (Subscribing to messages)

import { Effect, PubSub } from "effect"

const program = Effect.gen(function*() {
  const pubsub = yield* PubSub.bounded<string>(10)

  // Subscribe within a scope for automatic cleanup
  yield* Effect.scoped(Effect.gen(function*() {
    const subscription = yield* PubSub.subscribe(pubsub)

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

    // Take messages one by one
    const msg1 = yield* PubSub.take(subscription)
    const msg2 = yield* PubSub.take(subscription)
    console.log(msg1, msg2) // "Hello", "World"

    // Subscription is automatically cleaned up when scope exits
  }))

  yield* Effect.scoped(Effect.gen(function*() {
    const sub1 = yield* PubSub.subscribe(pubsub)
    const sub2 = yield* PubSub.subscribe(pubsub)

    // Multiple subscribers can receive the same messages
    yield* PubSub.publish(pubsub, "Broadcast")

    const [msg1, msg2] = yield* Effect.all([
      PubSub.take(sub1),
      PubSub.take(sub2)
    ])
    console.log("Both received:", msg1, msg2) // "Broadcast", "Broadcast"
  }))
})
subscriptions
Source effect/PubSub.ts:109212 lines
export const subscribe = <A>(self: PubSub<A>): Effect.Effect<Subscription<A>, never, Scope.Scope> =>
  Effect.uninterruptible(
    Effect.contextWith((services) => {
      const localScope = Context.get(services, Scope.Scope)
      const scope = Scope.forkUnsafe(self.scope)
      const subscription = makeSubscriptionUnsafe(self.pubsub, self.subscribers, self.strategy)
      return Scope.addFinalizer(scope, unsubscribe(subscription)).pipe(
        Effect.andThen(Scope.addFinalizerExit(localScope, (exit) => Scope.close(scope, exit))),
        Effect.as(subscription)
      )
    })
  )
Referenced by 4 symbols