Observer

Listener · Event emitter

Escrito por Darjus Kazakevic · revisado el

The thing that changed never learns who cared.

When an order is placed, you send an email, record a metric and refresh the search index. Each new reaction is another line in placeOrder(), and the order module ends up importing the mailer, the analytics client and the search code.

Observer reverses the direction. The subject announces an event, and listeners react without the subject knowing what they do. Node's EventEmitter and the DOM's addEventListener are this pattern. The costs: control flow is harder to follow, and a listener nobody removes is a memory leak.

En esencia — A subject keeps a list of listeners and calls each one when something happens, so adding a reaction never means editing the code that caused it.

Cuándo recurrir a él

Recurre a él cuando

  • Each new reaction to a change is another line in the method that made it
  • The subject's module has started importing mailers, metrics and caches
  • UI or in-process code where many parts react to one change

Reconsidéralo cuando

  • The caller needs a reaction's result, or must know it succeeded
  • Two fixed reactions that read more clearly as direct calls
  • Reactions must survive a crash: use an outbox and a message queue

Conceptos clave

Subject
The object that owns a list of listeners and announces events to them. It knows only the listener's signature, nothing about what listeners do.
Listener (observer)
A function called with each event. It must not assume other listeners ran first, and its errors must not break the subject.
Subscription handle
on() returns a function that removes the listener. Keep it, and call it when the owner (a request, a UI component, a connection) goes away.
In modern TypeScript
No observer interfaces are needed: a Set of functions is the whole subject. The platform's EventTarget also removes listeners for you when an AbortSignal fires.

Reglas de diseño

Every on() needs its off()
Subscribing returns the way out. A listener added per request and never removed keeps its closure alive, so memory grows and handlers run many times. Tie each one to an owner's lifetime.
Isolate listener failures
One listener that throws must not stop the others or fail the subject's own work. Catch and log per listener, or a broken receipt email can break order placement.
Notify over a copy of the listeners
A listener may unsubscribe itself, or add another, while it is being called. Loop over a copy, so changes made during an emit apply from the next emit.
Do not depend on listener order
Listeners run in the order they subscribed, which nobody controls on purpose. If B needs A's result, call A and then B directly instead.

Errores habituales

  • Subscribing per request or per component and never unsubscribing. Memory grows, and each event is handled many times.
  • Listeners that only work if another listener ran first.
  • Async listeners whose errors nobody catches, so a failed email becomes an unhandled promise rejection.
  • Using in-process observers for work that must not be lost. A crash after the database commit loses the email.