JavaScriptMedium
What is the Observer Pattern?
The Observer pattern lets an object (the subject) keep a list of dependents (observers) and notify them automatically when its state changes, so they stay in sync without the subject knowing what they do.
Structure
- Subject: holds state,
subscribe(observer),unsubscribe(observer),notify(). - Observers: callbacks or objects with an
updatemethod. subscribeusually returns an unsubscribe function, which makes cleanup easy.
Where you meet it
- DOM events (
addEventListeneris observer registration). - State libraries: Redux
store.subscribe, Zustand, MobX, signals. - React's
useSyncExternalStore, which subscribes components to any external store. IntersectionObserver,MutationObserver,ResizeObserver.- RxJS observables, WebSocket message handlers, Node's
EventEmitter.
Observer vs Pub/Sub
In Observer, observers subscribe directly to the subject. In Pub/Sub, publishers and subscribers communicate through a message broker or event bus using topics, and do not know about each other.
Pitfalls
- Memory leaks when observers forget to unsubscribe.
- Notification storms: many updates in a row trigger many notifications. Batch them (for example with a microtask).
- Order dependence between observers, and an observer throwing an error that stops others from being notified (wrap each call).
- Changing the observer list while notifying: iterate over a copy.
Code example
js
1class Observable {2 #state;3 #observers = new Set();4 constructor(initial) {5 this.#state = initial;6 }7 get state() {8 return this.#state;9 }10 #call(observer) {11 try {12 observer(this.#state);13 } catch (e) {14 console.log("observer failed:", e.message); // one bad observer doesn't stop others15 }16 }17 subscribe(observer) {18 this.#observers.add(observer);19 this.#call(observer); // send the current value immediately20 return () => this.#observers.delete(observer); // unsubscribe function21 }22 set(updater) {23 this.#state = typeof updater === "function" ? updater(this.#state) : updater;24 for (const observer of [...this.#observers]) this.#call(observer); // copy: safe if the list changes25 }26}2728const cart = new Observable({ items: 0 });29const badge = [];30const totals = [];3132const unsubscribeBadge = cart.subscribe((s) => badge.push(`badge: ${s.items}`));33cart.subscribe((s) => totals.push(`total: $${s.items * 10}`));34cart.subscribe(() => {35 throw new Error("broken widget");36});3738cart.set((s) => ({ items: s.items + 1 }));39unsubscribeBadge();40cart.set((s) => ({ items: s.items + 2 }));4142console.log(badge); // ["badge: 0", "badge: 1"] - stopped after unsubscribing43console.log(totals); // ["total: $0", "total: $10", "total: $30"]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.