Javascript Pub/Sub service

What exactly is it?

A Pub/Sub service is design pattern which enables to communicate between different modules of a web application without depending on each other. It allows publishers to send messages to subscribers without having to know anything about them. Publishers can publish messages to a topic, and subscribers can subscribe to that topic to receive messages from those topics.

This kind of design is mostly useful for building real-time web applications. For example, if we are building a chat app, we can use a Pub/Sub service to send messages from one user to another in real-time. This can be achieved as Pub/Sub service allows to handle events asynchronously.

How does it work ?

A Pub/Sub service typically consists of three main components:

  1. Publisher: A publisher is responsible for sending messages to a topics. This can be any part of the application that needs to send messages.
const subscribers = {};

function publish(topic, message) {
if (!Array.isArray(subscribers[topic])) {
return;
}
subscribers[topic].forEach(
(callback) => callback(message)
);
}

function subscribe(topic, callback) {
if (!Array.isArray(subscribers[topic])) {
subscribers[topic] = [];
}
const index = subscribers[topic].push(callback) - 1;
return {
unsubscribe() {
subscribers[topic].splice(index, 1);
}
}
}

export { publish, subscribe };


// Example usage

// Subscribing to a new topic
const subscription = pubSub.subscribe("event", data => {
console.log(`"event", was published with this data: ${data.msg}`);
})

// unsubscribing
subscription.unsubscribe();

// Publishing a message
const message = {
msg: "Publishing a new topic"
};
pubSub.publish("event", message);

In this example, we implemented a basic Pub/Sub pattern with two methods: subscribe and publish. The subscribe method is used to subscribe to a topic, and takes a topic name and a callback function as arguments.

The publish method is used to publish a message to a topic, and takes a topic name and a message object as arguments.

Let’s focus on the subscribe method.

function subscribe(topic, callback) {
if (!Array.isArray(subscribers[topic])) {
subscribers[topic] = [];
}
const index = subscribers[topic].push(callback) - 1;
return {
unsubscribe() {
subscribers[topic].splice(index, 1);
}
}
}

Subscribe method first check to see if the topic has been already registered in the subscribers object. If the topic doesn’t exist on the subscribers object, It register the topic using the topic name (first argument) as the key and initialise the value to an empty array. Lastly, we’ll push the subscriber callback into the event array. This function also returns an unsubscribe function with which subscribes can delete the topic subscription when no longer needed

The Publish service

function publish(topic, message) {
if (!Array.isArray(subscribers[topic])) {
return;
}
subscribers[topic].forEach(
(callback) => callback(message)
);
}

It checks if there are any subscribers that have registered for the topic. If there are no subscribers for that topic , It just returns from the function. If there are subscribers, it loop through the topic array and executes each subscriber callback that has been pushed into the topic array with the message publisher published.

Why should we use it ?

Loose coupling: One of the biggest advantages of using the publish/subscribe system is loose decoupling. As we already discussed publishers don’t know about the subscribers.

Scalability: It provides a way for scaling the system to a huge volume. This is because the pattern can handle the delivery of messages asynchronously, which means that it doesn’t block other parts of the application.

Happy PubSub ing!!!!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store