The Observer Pattern Explained: Events and Subscriptions
The observer pattern lets objects subscribe to changes in another object. Learn how it works, how to avoid leaks, and where it appears in real code.
By Velloreth
What the observer pattern does
The observer pattern lets one object notify many others when something changes, without knowing who they are.
The publisher maintains a list of subscribers. When its state changes, it iterates the list and notifies each one. Subscribers register and unregister themselves.
type Listener<T> = (value: T) => void;
class Observable<T> {
private listeners = new Set<Listener<T>>();
subscribe(listener: Listener<T>): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener); // unsubscribe
}
private notify(value: T): void {
for (const listener of this.listeners) listener(value);
}
}
Three things define the pattern:
- A way to subscribe.
- A way to unsubscribe.
- A way to notify all subscribers.
A complete example
class Store<T> {
private state: T;
private listeners = new Set<Listener<T>>();
constructor(initial: T) {
this.state = initial;
}
get(): T {
return this.state;
}
set(next: T): void {
this.state = next;
for (const listener of this.listeners) listener(next);
}
subscribe(listener: Listener<T>): () => void {
this.listeners.add(listener);
listener(this.state); // emit current value immediately
return () => this.listeners.delete(listener);
}
}
const store = new Store({ count: 0 });
const unsubscribe = store.subscribe((state) => {
console.log('count is', state.count);
});
store.set({ count: 1 }); // logs: count is 1
unsubscribe();
store.set({ count: 2 }); // no log
Two details are worth noting.
The Set prevents duplicate subscriptions. If the same listener subscribes twice, it is stored once. With an array, it would be called twice.
The immediate emit on subscribe is a design choice. It means subscribers do not need to read the current value separately. Some implementations do this; others do not. Be consistent.
The unsubscribe function
The most important practical detail is that subscribe returns an unsubscribe function.
const unsubscribe = store.subscribe(handler);
// later, when the handler is no longer needed
unsubscribe();
Without this, the publisher holds a reference to the subscriber forever. In a long-running application, that is a memory leak.
The leak is especially common in single-page applications. A component subscribes on mount, the user navigates away, the component is destroyed — but the subscription remains, holding the component and its data alive.
// React example
useEffect(() => {
const unsubscribe = store.subscribe(setState);
return unsubscribe; // cleanup on unmount
}, []);
The cleanup function is what prevents the leak. Forgetting it is the single most common observer bug.
Where the pattern appears
DOM events. addEventListener and removeEventListener are the observer pattern.
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);
Reactive frameworks. Vue’s reactivity, Svelte’s stores, and RxJS observables are all observer-based.
Message buses. An event bus lets unrelated parts of an application communicate.
bus.on('user:created', (user) => sendWelcomeEmail(user));
bus.on('user:created', (user) => createDefaultSettings(user));
WebSocket handlers. Each message type can have its own subscribers.
State management. Redux’s subscribe, MobX’s autorun, and Zustand’s subscribe all follow the pattern.
Node’s EventEmitter. The standard library’s event system.
File watchers and streams. fs.watch and stream events notify on change.
Observer vs pub-sub
The two are often conflated. The difference is the broker.
Observer: subscribers register directly with the publisher. The publisher knows its subscribers.
Publisher → Subscriber A
→ Subscriber B
Pub-sub: publishers and subscribers communicate through a broker. Neither knows the other.
Publisher → Broker → Subscriber A
→ Subscriber B
Pub-sub is more decoupled — a publisher can be replaced without touching subscribers — but it is harder to trace, because the connection is indirect. It also needs a broker, which is infrastructure.
Use observer when the relationship is direct and local. Use pub-sub when components should not know about each other at all.
Hot vs cold observables
A distinction that matters in reactive libraries.
Hot observables emit regardless of subscribers. A DOM event fires whether or not anyone is listening; a subscriber that joins late misses earlier events.
Cold observables start producing when subscribed. An HTTP request wrapped in an observable does not fire until someone subscribes, and each subscriber may trigger a separate request.
The distinction determines when work happens and whether late subscribers miss data. It is a common source of confusion in RxJS.
The downsides
Control flow is hard to trace. When a publisher notifies, the code that runs is not visible at the call site. Debugging means finding who subscribed.
store.set(newState); // what runs? unknown from here
Order is not guaranteed. With a Set, insertion order is preserved in JavaScript, but relying on it is fragile. Subscribers should not depend on each other’s execution order.
Errors propagate. If one listener throws, the loop stops and later listeners are not called. Wrap each call in a try/catch if that matters.
for (const listener of this.listeners) {
try {
listener(value);
} catch (error) {
console.error('Listener failed:', error);
}
}
Leaks. As discussed, forgetting to unsubscribe retains memory.
Cascading updates. A listener that triggers another update can cause a cascade, or an infinite loop if the updates feed back.
When to use it
Use observers when:
- One change must notify several independent consumers.
- The publisher should not know its consumers.
- Consumers come and go at runtime.
- You are building a reactive data layer.
Do not use observers when:
- There is exactly one consumer — use a callback or a promise.
- The flow is sequential — use direct calls.
- You need a return value — observers are fire-and-forget.
- The relationship is simple and static — direct calls are clearer.
The last point is the most important. Observers add indirection, and indirection has a cost. Use them where the decoupling is genuinely needed.
Practical guidance
- Always return and use the unsubscribe function.
- Use a
Setto prevent duplicate subscriptions. - Wrap listener calls in try/catch so one failure does not stop the rest.
- Emit the current value on subscribe if subscribers need it, and document the choice.
- Do not rely on listener order.
- Prefer a callback for a single consumer.
- Clean up in the framework’s unmount hook to avoid leaks.
- Consider whether pub-sub is needed — direct observer is simpler when it suffices.
For the related patterns, see design patterns for beginners and factory pattern explained. For the async context, event loop explained and callbacks explained.
Quotable summary
The observer pattern lets one object notify many subscribers when its state changes, without knowing who they are, through subscribe, unsubscribe, and notify. The unsubscribe function is essential, because the publisher holds a reference to every subscriber and forgetting to unsubscribe leaks memory — the most common observer bug in single-page applications. Observers decouple the publisher from its consumers, which is powerful but makes control flow harder to trace, since the code that runs on notification is not visible at the call site. The pattern underlies DOM events, reactive frameworks, message buses, and WebSocket handlers. Prefer a callback or promise when there is exactly one consumer; observers are for genuine one-to-many notification.