Tuesday, 25 September 2012

What is Pub Sub?

Every time you go on Facebook do you see updates to your news feed?

When you go on Twitter, do you see tweets from people you subscribed to?

Have you ever subscribed to blog's RSS feed and received updates to your feed reader?

Have you ever subscribed to an email newsletter on a particular topic of your interest?

What about when your computer has updates, it notifies you of them right? (often daily...which is always annoying!)

Well, underlying all these systems is a basic idea that you can subscribe to something and then when some new content is published, whether it is a status update, tweet, article, newsletter or the release of a new software, you will get notified of the update for as LONG AS YOU'RE SUBSCRIBED! As soon as you un-subscribe you will no longer get any updates.

This idea has popularly been shortened to the term "pub sub" which is geek speak for the publisher-subscribe pattern.

There are popular implementations of pub sub in all programming languages, but since I'm an advocate of JavaScript, please see this one I found here by Daniel Lamb:


In the documentation Daniel writes:
    //subscribe to a topic
    var handle = subscribe("/some/topic", function(msg){
        console.log(msg);
    });

    //publish topic a few times
    publish("/some/topic", ["first time"]);
    publish("/some/topic", ["second time"]);

    //unsubscribe from the topic
    unsubscribe(handle);

    //subscriber is no longer listening to the topic
    publish("/some/topic", ["message will not be logged"]);

For the purposes of web applications, users will be subscribing to particular URLs that receive updates to content and so this library would most likely be used on the server-side (e.g. Rhino, Node.js) to setup listeners on particular URLs.

Here are some alternative Pub Sub libraries for JavaScript:



No comments:

Post a Comment

Please leave your thoughts and comments!