Effect.ts: Absence as First-Class
Advanced Patterns • Lesson 43 of 51
43. PubSub - Broadcasting to Absent Subscribers
Values that exist for ALL subscribers, whenever they arrive
Code Example
const program = Effect.gen(function* () {
// Create PubSub - no subscribers yet (all absent!)
const pubsub = yield* PubSub.bounded<string>(10);
// Subscriber 1: waiting for absent values
const sub1 = yield* PubSub.subscribe(pubsub);
// Subscriber 2: also waiting
const sub2 = yield* PubSub.subscribe(pubsub);
// Publish: make value available to ALL
yield* PubSub.publish(pubsub, "Hello!");
// Both receive it!
const msg1 = yield* Queue.take(sub1); // "Hello!"
const msg2 = yield* Queue.take(sub2); // "Hello!"
// One message → multiple absence resolutions!
});
Interactive Example
const { PubSub, Queue } = await import('effect');
const program = Effect.gen(function* () {
const pubsub = yield* PubSub.bounded(10);
return yield* Effect.scoped(
Effect.gen(function* () {
const sub1 = yield* PubSub.subscribe(pubsub);
const sub2 = yield* PubSub.subscribe(pubsub);
yield* PubSub.publish(pubsub, 'Hello!');
const msg1 = yield* Queue.take(sub1);
const msg2 = yield* Queue.take(sub2);
return [msg1, msg2];
})
);
});
const [m1, m2] = await Effect.runPromise(program);
return `PubSub!
Published: "Hello!"
Sub 1 received: "${m1}"
Sub 2 received: "${m2}"
✓ Broadcast to all!`;
Explanation
PubSub: broadcasting to multiple absent consumers.
Traditional approach: each subscriber needs separate delivery. PubSub types broadcast absence:
- Subscribers are absent (don't exist yet)
- Messages are absent (not published yet)
- No assumptions about who subscribes when
- publish: resolve absence for ALL subscribers
- Late subscribers: still get messages!
Absence-first messaging: one source, many absent consumers!
Part 43 of 51 in the Effect.ts Absence Modeling series