Last active
February 23, 2021 10:23
-
-
Save wickedev/ff1a2ba66cfca630e771f92a5bfee9c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface IPubSub<T> { | |
publish(value: T): void; | |
subscribe(subscriber: Subscriber<T>): Disposer; | |
} | |
type Subscriber<T> = (value: T): void; | |
type Disposer = () => void; | |
class PubSub<T> implements IPubSub<T> { | |
private subscribers: ISubscriber<T>[] = []; | |
publish(value: T): void { | |
this.subscribers.forEach((subscriber) => { | |
subscriber(value); | |
}); | |
} | |
subscribe(subscriber: Subscriber<T>): Disposer { | |
this.subscribers.push(subscriber); | |
return () => { | |
const idx = this.subscribers.findIndex((s) => s === subscriber); | |
this.subscribers.splice(idx, 1); | |
}; | |
} | |
} | |
// Example | |
const pubsub = new PubSub<string>(); | |
pubsub.publish("greeting"); | |
const dispose = pubsub.subscribe((value: string) => { | |
console.info(value) | |
}); | |
dispose(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment