Skip to curriculum
Jump to the editor

19.2. Publish and subscribe

Easy
Topics
10–20 min

A shop page has a cart widget, a header badge and an analytics script. When an item is added, all three must hear about it, but the code that adds the item should not import any of them. A publish and subscribe hub decouples them: code publishes a message on a topic, and whoever subscribed to that topic receives it. Each subscriber holds a small function that ends its own subscription.

Write createPubSub() in pubsub.js.

Signature

JAVASCRIPT
function createPubSub() // returns { subscribe, publish, subscriberCount }

subscribe(topic, handler)  // returns unsubscribe()
publish(topic, data)       // returns the number of handlers called
subscriberCount(topic)     // returns a number
  • topic: any string. The topic "*" means "every topic".
  • handler(data, topic): called for each message.

Requirements

  1. publish(topic, data) calls each handler of topic with data and topic, in the order they subscribed.
  2. Topics are separate, and no name is special: "constructor" has no subscribers until one subscribes.
  3. publish returns how many handlers it called (0 when nobody listens).
  4. subscribe returns an unsubscribe function that ends that one subscription. Calling it again does nothing.
  5. The same handler subscribed twice runs twice, and each unsubscribe ends only its own subscription.
  6. Handlers subscribed to "*" receive every message, with its real topic, after the topic's own handlers. Publishing to "*" itself calls each of them once.
  7. A handler that throws does not stop the others: publish catches the error, reports it with reportError(error), and goes on. The count includes that handler.
  8. A handler subscribed during a publish first runs on the next one.
  9. subscribe throws a TypeError when handler is not a function, and stores nothing.
  10. Every hub has its own subscribers.

Examples

JAVASCRIPT
const hub = createPubSub();
const stop = hub.subscribe("cart:add", (item) => console.log("badge +1", item.id));
hub.subscribe("*", (data, topic) => console.log("analytics", topic));

hub.publish("cart:add", { id: 7 });  // "badge +1 7", then "analytics cart:add"; returns 2
stop();
hub.publish("cart:add", { id: 8 });  // "analytics cart:add"; returns 1
JAVASCRIPT
const hub = createPubSub();
hub.subscribe("save", () => { throw new Error("broken widget"); });
hub.subscribe("save", () => console.log("saved"));
hub.publish("save");  // "saved"; the error is reported, not thrown; returns 2
JAVASCRIPT
const hub = createPubSub();
hub.publish("nobody");                  // 0
hub.subscriberCount("constructor");     // 0

Environment

  • Plain JavaScript in a browser page; the tests call the global createPubSub from pubsub.js.
  • reportError(error) is a browser global: it reports the error as an uncaught one would be, without stopping your code.
  • Patterns such as "cart:*", asynchronous delivery and message history are not part of this problem.

Hints

  1. What can the unsubscribe function remember so it removes exactly one subscription, even when the same handler is there twice?
  2. When the topic is "*", which lists would you call, and is any of them called twice?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…