Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 57 ยท Behavioral Patterns

Observer

Learn the Observer design pattern: one subject notifies many observers when it changes. Covers push vs pull, EventEmitter, and memory leaks from forgotten unsubscribes.

The Observer pattern lets one object, the subject, tell any number of other objects, the observers, when something happens to it. The subject does not know who the observers are or what they do. It only knows that each one has a method it can call. Observers sign up (subscribe) when they care and sign off (unsubscribe) when they do not.

You already use this idea every day. A button on a web page does not know which code reacts to a click. A stock ticker does not know which screens show its price. A build server does not know who wants an email when a build fails. In each case the thing that changes is decoupled from the things that react, so you can add a new reaction without touching the original.

Publish once, reach many

Subject Holds the state and a list of listeners.
Observers Each one reacts in its own way.
Loose coupling The subject never learns what its observers do.

Adding an observer never means editing the subject.

1 / 2

The structure

The subject keeps a list of observers and offers three operations: subscribe, unsubscribe and notify. Every observer implements one small interface, usually a single method such as update.

sequenceDiagram
    participant O as Observer
    participant S as Subject
    O->>S: subscribe(observer)
    Note over S: state changes
    S->>O: update(data)
    O->>S: unsubscribe(observer)

The subject calls every subscribed observer when its state changes; observers can leave at any time.

In a classic class-based design, Subject has attach(observer), detach(observer) and notify(), and Observer is an interface with update(...). In JavaScript and Python you can skip the interface and subscribe plain functions.

Push or pull

When the subject notifies, there are two ways to hand over the information:

  • Push. The subject sends the new data along with the notification: update(newPrice). Observers get what they need immediately, but the subject must guess what data is useful, and it may send more than some observers want.
  • Pull. The subject only says "I changed" and passes itself: update(subject). Each observer then asks for exactly the pieces it wants, such as subject.getPrice(). This is more flexible, but observers become coupled to the subject's getters.

Most event systems push a small event object that carries the details, which is a good middle ground.

A hand-written subject

Here is the pattern with no library. The subject returns an unsubscribe function from subscribe, which is a convenient modern idiom: whoever subscribes holds the only key needed to leave.

JS A price ticker with observers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The ticker never mentions logging or alarms. You can add an observer that writes to a database without changing a line of PriceTicker.

Observer with Node's EventEmitter

Node.js ships the pattern in its standard library as EventEmitter. Instead of one update method, a subject can emit many named events, and observers subscribe to the names they care about with on. Here is the same idea on a small order service. This block runs on our Node 24 runner.

Node.js EventEmitter: one subject, several named events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Three details of EventEmitter are worth knowing:

  • Listeners run synchronously, in the order they were added, before emit returns. If one is slow, everyone waits.
  • once subscribes a listener that removes itself after the first call.
  • Emitting an event named "error" with no listener throws, so always attach an error listener to emitters that can fail.

EventEmitter is real Node.js code and the block above runs on the real runtime. The browser equivalent is EventTarget with addEventListener; the idea is identical.

The silent leak: forgotten unsubscribes

The subject holds a reference to every observer. That means an observer that is still subscribed can never be garbage collected, even if the rest of your program has forgotten it exists. This is the classic lingering listener leak. It grows when short-lived objects (a dialog, a page, a request handler) subscribe to long-lived subjects (an application-wide event bus) and never unsubscribe.

Node even warns about it: by default, adding more than 10 listeners for one event name on one emitter prints a "possible EventEmitter memory leak" warning, which is a hint that something is subscribing in a loop.

JS Finding and fixing a lingering listener

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The fix is discipline: whoever subscribes must also unsubscribe, ideally in the same place that tears the object down. Returning an unsubscribe function, as above, makes this easy. In the browser, addEventListener accepts an AbortSignal, so one abort() removes many listeners at once. Another defence is a weak reference so the subject does not keep observers alive, but it makes timing less predictable, so explicit unsubscribing is the usual answer.

Other pitfalls

  • Surprising order. Do not write observers that depend on running before or after another observer.
  • Change during notification. An observer that subscribes or unsubscribes while the subject is looping can corrupt the loop. Copy the list first, as the emit above does.
  • Cascades. An observer that changes the subject, directly or through another subject, can trigger a chain of updates or an infinite loop.
  • Hard-to-follow flow. When behavior is wired up through events, reading the code no longer shows who reacts to what. Name events clearly and keep the number of subjects small.

Observer is the foundation of event-driven programming and of reactive libraries. When the reactions form a sequence of steps for one request, a Chain of Responsibility fits better; when objects need to talk to each other in many directions, a mediator centralizes the traffic. If you need to swap a single algorithm rather than broadcast to many listeners, see Strategy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the subject know about its observers?

    The subject keeps a list of things it can call and nothing more, which is what keeps it decoupled from the reactions.
  2. 2. In the pull variant of Observer, what does the notification carry?

    Pull sends 'I changed' plus the subject itself; each observer then reads only the values it needs. Push sends the data with the notification.
  3. 3. A short-lived dialog subscribes to a long-lived application event bus and is never unsubscribed. What is the likely result?

    The subject's list holds a strong reference to each observer. Without an unsubscribe, the observer outlives its usefulness: a lingering listener leak.
  4. 4. When does an EventEmitter call its listeners?

    emit runs every listener for that event immediately and in the order they were added, so a slow listener delays the emitter and the other listeners.
  5. 5. Why does the hand-written emit copy the handler set before looping?

    Changing a collection while you iterate it can skip or repeat entries. Iterating over a copy makes the notification round stable.

Summary

  • Observer lets a subject notify many observers without knowing who they are or what they do.
  • Subscribing, unsubscribing and notifying are the three operations; an unsubscribe function is a handy return value.
  • Push sends the data with the notification; pull sends the subject and lets observers ask.
  • Node's EventEmitter and the browser's EventTarget are real-world implementations; emitters call listeners synchronously in order.
  • A subscription is a strong reference: always unsubscribe, or you create lingering-listener memory leaks.
  • Watch for ordering assumptions, changes during notification and update cascades.

Next lesson: Command.