Skip to content

Broadcast

Defined in: packages/async/src/synchro/broadcast.ts:96

A broadcast channel that allows multiple subscribers to receive messages.

Each subscriber maintains its own message queue with a specified capacity. If a subscriber’s queue is full when a new message is sent, the oldest message in that subscriber’s queue is discarded to make room for the new message.

const broadcast = new Broadcast<number>(5); // Capacity of 5 messages per subscriber
// Subscriber 1
const subscriber1 = broadcast.subscribe();
function listen1() {
while (!subscriber1.closed) {
const msg = await subscriber1.receive();
console.log("Subscriber 1 received:", msg);
}
}
listen1();
// Subscriber 2
const subscriber2 = broadcast.subscribe();
function listen2() {
while (!subscriber2.closed) {
const msg = await subscriber2.receive();
console.log("Subscriber 2 received:", msg);
}
}
listen2();
// Send messages
await broadcast.send(1);
await broadcast.send(2);
// Close the broadcast channel
broadcast.close();

T extends DefinedValue

The type of messages carried. Anything except undefined, which the subscriber queues reserve for “no message”.

new Broadcast<T>(capacity): Broadcast<T>

Defined in: packages/async/src/synchro/broadcast.ts:109

Creates a new Broadcast channel.

All subscribers will have their own message queue with the specified capacity.

number

The capacity of each subscriber’s message queue.

Broadcast<T>

If the capacity is less than or equal to zero.

get closed(): boolean

Defined in: packages/async/src/synchro/broadcast.ts:116

Indicates whether the broadcast channel is closed.

boolean

close(): void

Defined in: packages/async/src/synchro/broadcast.ts:168

Closes the broadcast channel.

void


send(message): void

Defined in: packages/async/src/synchro/broadcast.ts:150

Sends a message to all subscribers.

T

The message to send.

void

A promise that resolves when the message has been sent to all subscribers.


subscribe(): IBroadcastSubscriber<T>

Defined in: packages/async/src/synchro/broadcast.ts:125

Subscribe to the broadcast channel.

IBroadcastSubscriber<T>

A new subscriber to the broadcast channel.