Patterns & principles · 4 of 10 · 13 min read
Observer and Pub/Sub
One object notifying many, the broker that decouples them further, and the unsubscribe everybody forgets.
- Design patterns
One object changes, and others need to know. The Observer pattern is the arrangement where the changing object — the subject — keeps a list of interested parties and calls them when something happens.
Observer
class Subject {
#observers = new Set();
subscribe(observer) {
this.#observers.add(observer);
return () => this.#observers.delete(observer); // the unsubscribe
}
notify(data) {
for (const observer of this.#observers) observer(data);
}
}
const stock = new Subject();
const unsubscribeChart = stock.subscribe((price) => console.log('chart:', price));
stock.subscribe((price) => console.log('alert:', price));
stock.notify(42);
// chart: 42
// alert: 42
unsubscribeChart();
stock.notify(43);
// alert: 43
Two details that make this version usable rather than merely correct:
subscribereturns its own unsubscribe. The caller never has to keep a reference to the function it passed, which is the usual reason listeners are never removed.- A
Set, not an array. Subscribing the same function twice has no effect, and removal is O(1).
The subject knows nothing about what its observers do. That is the decoupling: adding a logger does
not change Subject.
Pub/Sub
Now put a broker in the middle. Publishers emit to a topic; subscribers listen to a topic; neither holds a reference to the other.
function createBus() {
const topics = new Map();
return {
on(topic, handler) {
if (!topics.has(topic)) topics.set(topic, new Set());
topics.get(topic).add(handler);
return () => topics.get(topic)?.delete(handler);
},
emit(topic, payload) {
for (const handler of topics.get(topic) ?? []) handler(payload);
},
off(topic) {
topics.delete(topic);
},
};
}
const bus = createBus();
const off = bus.on('order:created', (order) => console.log('email for', order.id));
bus.on('order:created', (order) => console.log('invoice for', order.id));
bus.emit('order:created', { id: 7 });
// email for 7
// invoice for 7
off();
bus.emit('order:created', { id: 8 }); // invoice for 8
| Observer | Pub/Sub | |
|---|---|---|
| Who holds the list | the subject itself | a separate broker |
| Do the two sides know each other | the observer knows the subject | neither knows the other |
| Addressed by | the object | a topic string |
| Typical use | one model, a few views | modules across an app |
| Easy to trace | yes — one subject to read | no — who emits order:created? |
That last row is the real trade-off and the honest answer to “which is better?”. Pub/Sub decouples so thoroughly that finding what responds to an event means grepping for a string. On a small app that is freedom; on a large one it is a debugging tax.
The platform ships both
You almost never need to write either. EventTarget is Observer:
class Store extends EventTarget {
#value = 0;
set(value) {
this.#value = value;
this.dispatchEvent(new CustomEvent('change', { detail: value }));
}
}
const store = new Store();
store.addEventListener('change', (e) => console.log('changed to', e.detail));
store.set(5); // changed to 5
Node’s EventEmitter is the same idea with a terser API:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.on('tick', (n) => console.log('tick', n));
emitter.once('ready', () => console.log('only the first time'));
emitter.emit('ready');
emitter.emit('ready'); // nothing
emitter.emit('tick', 1); // tick 1
And a promise is an observer with exactly one event that fires exactly once — which is why .then
replaced callbacks for single results but not for repeated ones.
Unsubscribing
This is the part that fails in production. A subscription keeps a reference to the handler, the handler closes over a component, and the component is therefore never collected:
function mountChart(bus) {
const bigData = new Array(1e6).fill(0);
bus.on('tick', () => console.log(bigData.length)); // never removed
}
// Every mount adds a handler that pins a megabyte. Unmounting changes nothing.
Three ways to get it right:
// 1. Keep the returned unsubscribe.
const off = bus.on('tick', handler);
off();
// 2. AbortController — one signal removes any number of listeners.
const controller = new AbortController();
element.addEventListener('click', onClick, { signal: controller.signal });
element.addEventListener('keydown', onKey, { signal: controller.signal });
controller.abort(); // both gone
// 3. `once`, when the event can only matter one time.
element.addEventListener('load', onLoad, { once: true });
AbortController is the one to reach for in modern code: one abort() in a cleanup function
removes every listener registered with that signal, and it works for fetch too.
Hardening the emit loop
A naive for (const h of handlers) h(data) has two bugs that only appear under load.
A throwing handler stops the rest:
const bus = createBus();
bus.on('x', () => { throw new Error('boom'); });
bus.on('x', () => console.log('never runs'));
// bus.emit('x'); // the error escapes and the second handler is skipped
A handler that subscribes or unsubscribes during the emit mutates the set being iterated. Copying first fixes both:
function emit(topic, payload) {
for (const handler of [...(topics.get(topic) ?? [])]) { // a snapshot
try {
handler(payload);
} catch (error) {
console.error(`handler for ${topic} failed`, error); // one failure, not all
}
}
}
Whether handlers should run synchronously is a real decision: synchronous is easier to reason about and makes the emitter’s caller pay for slow handlers; queueing them as microtasks protects the caller but makes ordering harder to follow.
Common mistakes
Subscribing an inline arrow and trying to remove it later
Mistake. bus.on('tick', () => update()) and then bus.off('tick', () => update()).
Why it fails. Two arrow functions are two different objects, so the removal matches nothing.
What to do instead. Keep the reference, or use the unsubscribe the subscribe call returned.
Letting the subject know about its observers
Mistake. if (observer.type === 'chart') observer.redraw() inside notify.
Why it fails. The subject now depends on the observers, which is exactly the coupling the
pattern exists to remove — and every new observer type edits the subject.
What to do instead. Call one agreed function and let each observer decide what to do.
Using an event bus as the app’s data flow
Mistake. Routing state changes between modules through topic strings. Why it fails. Nothing can be traced: the chain of cause and effect is a set of strings with no compiler, no types and no call graph. What to do instead. Direct calls or a state container for data flow; keep the bus for genuinely broadcast, fire-and-forget notifications.
Check yourself
2 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does the Observer pattern describe?
What distinguishes Pub/Sub from the plain Observer pattern?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.