Created
November 13, 2019 14:17
-
-
Save alperg/79bd3774842a50cc50c8fdadbfbe6f83 to your computer and use it in GitHub Desktop.
PubSub with observer pattern
This file contains 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
class PubSub { | |
constructor () { | |
this.subIds = 0; | |
this.subscriptions = {} | |
} | |
subscribe (topic, fn) { | |
if(!this.subscriptions[topic]) this.subscriptions[topic] = {} | |
const token = ++this.subIds; | |
// Validate topic name and function constructor | |
this.subscriptions[topic][token] = fn; | |
return () => this.unsubscribe(topic, token) | |
} | |
publish (topic, ...args) { | |
const subs = this.subscriptions[topic]; | |
if(!subs) return false | |
Object.values(subs).forEach(sub => sub(...args)) | |
} | |
unsubscribe (topic, token) { | |
if(!token) delete this.subscriptions[topic]; // Delete all subscriptions for the topic | |
this.subscriptions[topic] && (delete this.subscriptions[topic][token]); // Delete specific subscription | |
} | |
} | |
export default new PubSub(); |
This file contains 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
const unsub1 = PubSub.subscribe('spacex', data => console.log('Falcon was launched', data)); | |
const unsub2 = PubSub.subscribe('spacex', data => console.log('Falcon Heavy was launched', data)); | |
PubSub.publish('spacex', 'some data slash params') | |
// Unsubscribe single subscription | |
unsub1(); // Unsubscribes Falcon | |
unsub2(); // Unsubscribes Falcon Heavy | |
// Unsubscribe ALL subscriptions for a topic | |
PubSub.unsubscribe('spacex') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment