createObservable()
createObservable<
T>():object
Creates an observable (pub/sub emitter). Replaces the GoF Subject class - no interface, no attach/detach ceremony, just subscribe and get back an unsubscribe function.
Type Parameters
T: T
The type of values emitted to listeners
Returns
Observable with subscribe, notify, once, safeNotify, size, clear
subscribe(): (listener) => Unsubscribe
Add a listener. Returns an unsubscribe function.
listener:
Listener<T>
Returns:Unsubscribe
notify(): (value) => void
Emit a value to all listeners. Fail-fast: if a listener throws,
the error propagates and subsequent listeners are not called.
Use safeNotify for resilient notification.
value:
T
Returns:void
once(): (listener) => Unsubscribe
Subscribe for a single notification, then auto-unsubscribe.
The listener is wrapped internally - always use the returned
Unsubscribe function to cancel before it fires.
listener:
Listener<T>
Returns:Unsubscribe
safeNotify(): (value) => Result<void, Error[]>
Emit a value to all listeners with error safety.
Unlike notify, this catches listener errors and continues
notifying remaining listeners. Returns a zygos Result:
Ok(void)if all listeners succeededErr(Error[])with collected errors from failing listeners
value:
T
Returns:Result<void, Error[]>
Since
2.4.0
size
Get Signature: > *get size*(): number
Current number of listeners.
Returns: number
clear(): () => void
Remove all listeners.
Returns: void
Since
2.4.0
Example
const onUserLogin = createObservable<{ id: string; name: string }>();
// Subscribe - returns an unsubscribe function
const unsub = onUserLogin.subscribe((user) => {
console.log(`${user.name} logged in`);
});
// One-time listener
onUserLogin.once((user) => {
sendWelcomeEmail(user);
});
onUserLogin.notify({ id: "1", name: "Alice" });
unsub();
Listener()<T>
Listener<
T> = (value) =>void
A listener is a callback that reacts to emitted values. Replaces the GoF Observer interface.
Type Parameters
T: T
The value type
Parameters
value: T
Returns: void
Since
2.4.0
Unsubscribe()
Unsubscribe = () =>
void
A function that removes a listener when called.
Replaces the GoF detach(observer) method.
Returns: void
Since
2.4.0