Skip to content

Instantly share code, notes, and snippets.

@dheerajsuthar
Created December 6, 2018 21:17
Show Gist options
  • Save dheerajsuthar/f9668e9a6a2c36d36f58bca1f3efec6f to your computer and use it in GitHub Desktop.
Save dheerajsuthar/f9668e9a6a2c36d36f58bca1f3efec6f to your computer and use it in GitHub Desktop.
Publisher Subscriber Manager
class PubSubManager {
constructor() {
this.channels = {
weather: {
message: '',
subscribers: []
},
sports: {
message: '',
subscribers: []
}
}
this.brokerId = setInterval(() => { this.broker() }, 1000);
}
subscribe(subscriber, channel) {
console.log(`subscribing to ${channel}`);
this.channels[channel].subscribers.push(subscriber);
}
removeBroker() {
clearInterval(this.brokerId);
}
publish(publisher, channel, message) {
this.channels[channel].message = message;
}
broker() {
for (const channel in this.channels) {
if (this.channels.hasOwnProperty(channel)) {
const channelObj = this.channels[channel];
if (channelObj.message) {
console.log(`found message: ${channelObj.message} in ${channel}`);
channelObj.subscribers.forEach(subscriber => {
subscriber.send(JSON.stringify({
message: channelObj.message
}));
});
channelObj.message = '';
}
}
}
}
}
module.exports = PubSubManager;
@david-fong
Copy link

I think the broker key loop can use Object.getOwnPropertyNames.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment