Skip to content

Instantly share code, notes, and snippets.

@dkacper
Created April 26, 2024 13:15
Show Gist options
  • Save dkacper/c79a53beb4574f5ce2c36e8b4fe80d1d to your computer and use it in GitHub Desktop.
Save dkacper/c79a53beb4574f5ce2c36e8b4fe80d1d to your computer and use it in GitHub Desktop.
Publish-subscriber. Implementation of observer pattern in TypeScript.
type Subscriber<TData> = (data: TData) => void;
interface IPublisher<TEvent, TData> {
subscribe(event?: TEvent): (subscriber: Subscriber<TData>) => () => void;
notify(event: TEvent, data: TData): void;
}
export class Publisher<TEvent, TData> implements IPublisher<TEvent, TData> {
protected subscribers: { event: TEvent; subscriber: Subscriber<TData> }[] = [];
public subscribe = (event?: TEvent) => (subscriber: Subscriber<TData>) => {
this.subscribers.push({ event, subscriber });
return () => {
this.subscribers = this.subscribers.filter(
(sub) => subscriber !== sub.subscriber
);
};
};
public notify = (event: TEvent, data: TData) => {
for (const sub of this.subscribers) {
if (sub.event === event || !sub.event) {
sub.subscriber(data);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment