Observer: notifying without knowing who listens

  • Lesson 19 of 32
  • 10 min
  • Beginner
  • 12 steps

A cart that, every time you add a product, calls by hand everything that has to react. You will give it a list of subscribers and see what you gain, what breaks if you forget to remove them, and when a direct call is better.

Classes Cart knows
0
Listeners on «added»
3
ShopCartCartBadgeBadge ·unmountedBadgeAnalyticsAnalyticsRecosRecos ·not subscribedRecosListenerinterfaceListenerCartCartBadgeBadgeAnalyticsAnalyticsknows Badge and AnalyticsCart calls each oneclass Cart {add(sku: string) {this.items.push(sku);▸this.badge.increment();▸this.analytics.track(sku);}}new reactionedit Cart againOne more reactionclass Cart {add(sku: string) {this.items.push(sku);this.badge.increment();this.analytics.track(sku);+this.recos.refresh(sku);}}only knows ListenerThe contractinterface Listener {▸onAdded(sku: string): void;}class Badge implements Listener {…}class Analytics implements Listener {…}cart.on(badge)cart.on(analytics)Subscribeclass Cart {private ls: Listener[] = [];on(l: Listener) {▸this.ls.push(l);}}cart.on(badge);cart.on(analytics);add("SKU-1")notifies the listNotifyclass Cart {add(sku: string) {this.items.push(sku);▸for (const l of this.ls)▸l.onAdded(sku);}}cart.on(recos)Cart unchangedSetup (Cart unchanged)// when the app startscart.on(badge);cart.on(analytics);+cart.on(recos);cart.add("SKU-1");add() waits for all 31st2nd3rdNode: EventEmitterconst cart = new EventEmitter();cart.on("added", s => log("badge"));cart.on("added", s => log("stats"));cart.on("added", s => log("recos"));▸cart.emit("added", "SKU-1");log("after emit");// badge · stats · recos// after emitwarning: over 10still receivingThe missing offfunction mount() {cart.on("added", update);}function unmount() {el.remove();▸// cart.off(...) is never called}off() on unmountUnsubscribeconst ctrl = new AbortController();btn.addEventListener("click", onClick,{ signal: ctrl.signal });cart.on("added", update);// on unmount:+cart.off("added", update);+ctrl.abort(); // drops the clicknot there: misses itThree misconceptions«they are async»emit calls them right away«order does not matter»registration order«it is a queue»in memory: nobody there, lostthrownever calledWhen not to use ita required stepcall it directlya listener throwsit comes out of add()events that trigger eventsa flow nobody can follownotifies without knowing anyoneObserver in a tableproblemCart calls each reactionsolutionlistener list + notifynew reactioncart.on(), Cart unchangedcarefulevery on with its offskip itfor a required step
  • request
  • response
  • event
  • failed request

Step 1 of 12

Problem

The cart knows everyone who reacts

In a shop, when someone adds a product, two things happen: the badge on the cart icon goes up by one and analytics records the product.

Cart.add() makes both calls by name: this.badge.increment() and this.analytics.track(sku). It works, but Cart depends on two classes that have nothing to do with storing products.

Step 2 of 12

Problem

Every new reaction edits the cart

Now product asks for suggestions: when something is added, refresh the «you may also like» list. That means opening Cart, injecting Recos and adding another line to add().

The cart now knows 3 classes, and every future reaction means touching it and testing it again. If one of those classes changes its method, Cart breaks too.

What changed

  • Recos
  • Cart.add()

Step 3 of 12

Concept

The notifier only knows an interface

The idea of Observer: the subject (Cart) keeps a list of observers and notifies them when something happens. It does not know what each one does with the notice.

All they share is a contract, Listener, with one method onAdded(sku). Badge and Analytics implement it (dashed line with a hollow triangle); Cart only talks to Listener.

What changed

  • interface Listener

Step 4 of 12

Technique

Each interested party joins the list

Cart gets an on(l) method that does one thing: push the listener onto its list. Whoever wants to hear about it subscribes; the cart picks no one.

When the app starts, the setup code calls cart.on(badge) and cart.on(analytics). The list holds 2 listeners and Cart knows neither class.

What changed

  • Cart.on(l)
  • this.badge, this.analytics

Step 5 of 12

Solution

add() walks the list and notifies

Now add() stores the product and then walks the list, calling onAdded(sku) on each listener. The code is the same with 2 listeners or 20.

The badge goes up by one and analytics records the product, as before. The difference is the dependency: the arrow no longer goes from the cart to each class, it goes from each class to the contract.

What changed

  • for (const l of this.ls) l.onAdded(sku)

Step 6 of 12

Solution

Suggestions arrive without touching Cart

Back to suggestions. With Observer it is one line in the setup: cart.on(recos). Cart does not change, and neither do its tests.

From the next add() on, suggestions get the notice along with the other two. Before, the cart had to be edited for every new reaction; now, 0 times.

What changed

  • cart.on(recos)

Step 7 of 12

Technique

emit calls everyone before it returns

Node ships this already: EventEmitter, with on to subscribe and emit to notify. Its documentation says emit calls the listeners synchronously, in the order they were registered.

In the example (log is console.log), it prints badge, then stats, then recos, and only then after emit. add() does not finish until the last listener finishes: one slow listener makes the cart slow.

Step 8 of 12

Problem

The component left, its listener did not

The badge is a UI component: it mounts when the page opens and unmounts when you leave. On mount it calls cart.on, but on unmount nobody calls cart.off.

The listener stays on the list, the cart keeps notifying a component that is no longer on screen, and the memory is never freed. After 9 badge mounts, added has 9 + 1 + 1 = 11 listeners (example values).

Step 9 of 12

Solution

Whoever subscribes also unsubscribes

The rule: every `on` has its `off` at unmount, with the same function. In the DOM it is removeEventListener; for a notice that matters only once, the once option removes it for you.

Another DOM way: pass a signal from an AbortController when you subscribe. Calling abort() removes every listener that used that signal. The badge is back to 1 listener per mount: 3 in total.

What changed

  • cart.off("added", update)
  • ctrl.abort()

Step 10 of 12

Concept

Observer is not a message queue

Three common misconceptions. «Observers are asynchronous»: with EventEmitter, they are not. «Order does not matter»: they run in registration order, and if one depends on another, that order matters.

«It is the same as a queue»: no. Everything happens in memory, inside one process. If suggestions were not subscribed when you emitted, they miss the notice and nobody keeps it. That is what pub/sub with a broker is for, covered in the pub/sub lesson of the System Design course.

Step 11 of 12

Trade-off

When a direct call is better

If a reaction must succeed for the operation to succeed (reserving stock, charging a card), do not hide it behind an event: call it directly and handle its error. And since the call is synchronous, a throw inside a listener comes out of add() and the remaining listeners are not called.

Watch out for events that trigger events too: the flow stops reading in the code, and debugging turns into guessing who listens to what.

Step 12 of 12

Summary

Notify a list, not names

When a class calls, by name, everything that reacts, give it a list of subscribers: each interested party joins with on, the class notifies with a loop, and a new reaction does not touch it.

Remember that emit is synchronous and in order, that every on needs its off, and that a required step gets a direct call.

You will learn

  • Recognise the problem: a class that calls, by name, everything that must react.
  • Separate who notifies from who listens with an interface and a list of subscribers.
  • Know that `emit` calls the listeners right away and in the order they were registered.
  • Remove listeners with `off`, `removeEventListener`, `once` or `signal` so nothing leaks.
  • Know when an Observer is overkill and how it differs from a message queue.