@cdellacqua/signals
Version:
A simple signal pattern implementation that enables reactive programming
52 lines (51 loc) • 1.72 kB
TypeScript
/** A generic subscriber that takes a value emitted by a signal as its only parameter. */
export declare type Subscriber<T> = (current: T) => void;
/** A function that's used to unsubscribe a subscriber from a signal. */
export declare type Unsubscribe = () => void;
/** A signal that can have subscribers and emit values to them. */
export declare type ReadonlySignal<T> = {
/**
* Subscribe a function to this signal.
*
* Note: subscribers are deduplicated, if you need to subscribe the same
* function more than once wrap it in an arrow function, e.g.
* `signal$.subscribe((v) => myFunc(v));`
* @param subscriber a function that will be called when this signal emits.
*/
subscribe(subscriber: Subscriber<T>): Unsubscribe;
/**
* Subscribe a function to this signal and automatically unsubscribe it after one emit occurs.
*
* @param subscriber a function that will be called when this signal emits.
*/
subscribeOnce(subscriber: Subscriber<T>): Unsubscribe;
/**
* Return the current number of active subscriptions.
*/
nOfSubscriptions(): number;
};
/** A signal that can have subscribers and emit values to them. */
export declare type Signal<T> = ReadonlySignal<T> & {
/**
* Emit a value to all subscribers.
* @param v the value to emit.
*/
emit(v: T): void;
};
/**
* Make a signal of type T.
*
* Example usage:
* ```ts
* const signal$ = makeSignal<number>();
* signal$.emit(10);
* ```
* Example usage with no data:
* ```ts
* const signal$ = makeSignal<void>();
* signal$.emit();
* ```
* @returns a signal.
*/
export declare function makeSignal<T>(): Signal<T>;
export * from './composition';