Implements Publisher/Subscriber pattern. Provides a value emitter, subscription and consumer interface. Supports Typescript.
Install dependencies:
$ npm install --save @mnasyrov/pubsub
Create an emitter and publish a value to consumers:
import {Emitter} from '@mnasyrov/pubsub';
// Declare a value emitter.
const emitter = new Emitter<number>();
// Subscribe by a listener.
const subscription = emitter.subscribe(value => {
console.log(value);
});
// Emit a value.
emitter.emit(42);
// Cancel a subscription.
subscription.unsubscribe();
/** Allows to cancel a subscription. It is compatible with RxJS/Subscription. */
export interface Subscription {
unsubscribe(): void;
}
export type Consumer<T> = (value: T) => any;
export interface Publisher<T> {
subscribe(consumer: Consumer<T>): Subscription;
}
export interface Emitter<T> {
constructor();
/** A number of subscribed consumers. */
readonly size: number;
/** Subscribes a consumer of values. */
subscribe(consumer: Consumer<T>): Subscription;
/** Emits a value to subscribed consumers. */
emit(value: T);
/** Removes all subscribed consumers. */
clear();
}