signal
Create a transient payload source using the observable package's subscription pattern.
Import
import { signal } from '@bedrock-core/observable';
import type { Signal } from '@bedrock-core/observable';
Signature
signal<T>(): {
subscribe(listener: (event: T) => void): Unsubscribe;
emit(payload: T): void;
}
Returns
| Member | Behavior |
|---|---|
emit(payload) | Notify current subscribers synchronously |
subscribe(listener) | Receive future payloads; returns an idempotent unsubscribe function |
Signal<T> describes subscriptions without an emitter or retained value. Keep the emitter with the owner and export a Signal<T> view from public addon APIs. Repeated identical payloads and undefined payloads are separate occurrences. Nothing is retained or replayed.
signal() exposes only subscribe and emit; it has no unsubscribe method. Each returned cleanup removes only its own registration, even when the same callback is subscribed more than once.
Local subscribers receive the emitted value directly: signal() neither clones nor freezes payloads. Emission iterates the listeners present when it begins. Newly added listeners wait for the next emission; removing a listener during delivery does not remove it from that in-progress iteration. Listener exceptions are reported and the remaining callbacks still run.
Usage
const purchases = signal<{ playerId: string; gold: number }>();
const stop = purchases.subscribe(({ playerId, gold }) => {
updateBalance(playerId, gold);
});
purchases.emit({ playerId: player.id, gold: 5 });
stop();
Native event sources
Signal<T> always returns a cleanup function from subscribe. Native event sources use the separate NativeSignal<T, Options> type. Convert them with toSignal before handing them to code that expects a Signal.
Notes
Use observable for a current value with get. Use last to retain a signal's most recent payload as a read-only observable. Public addon APIs use the same Signal<T> contract. Internal subscriptions and imported API handles use cleanup returns. External sources are normalized at the boundary.