Learn

Architecture & pattern guides

Read the idea, build it on a Grid, prove it in a challenge. Short, practical guides — illustrated with RodGrid's own nodes — on system design, design patterns, flow modeling, and how to get the most out of the app.

All articles

Observer

A subject keeps a list of observers and notifies each of them through one small interface, so new observers arrive without changes to the subject, and the price of that freedom shows up in slow observers, out-of-order changes and listeners nobody removed.

Five calls at the end of setText

In the first version of a text editor, Document.setText ended with five calls: gutter.renumber(this), statusBar.updateWordCount(this), minimap.redraw(this), spellChecker.recheck(this) and autosave.schedule(). Showing a reading-time estimate in the status bar meant adding a sixth.

The class that holds the text knew five user-interface classes and what each wanted to hear. Every feature that cared about the text meant another import and another line in setText, and a plugin, whose author cannot edit Document, had no way in at all.

A list instead of names

Observer turns that dependency around. The document, now the subject, stops naming the things that react to it. It keeps a list of observers, objects that implement one small interface, say onTextChanged(document), and offers subscribe(observer) to add one to the list and unsubscribe(observer) to remove it. When the text changes, setText walks the list and calls onTextChanged on each entry. That call is the notification.

The result is a one-to-many dependency: when the subject changes, every registered observer is notified, and the subject knows only the observer interface, so observers come and go freely. The reading-time estimate becomes one more class with an onTextChanged method, registered by the status bar, and Document does not change.

The document notifies its observers

Document keeps a list and calls each entry through the same interface. It imports none of the observers' classes.

Watch outIf the subject imports concrete observer classes and calls them by name instead of through the observer interface, you are back at the five calls: adding a new observer means editing the subject.

What the notification carries

Sending only the document is the pull style: each observer asks the subject for whatever it needs. The interface stays tiny, and an observer written next year can read anything the document exposes. The cost showed up in the minimap. To repaint only what changed it needed to know which lines had changed, the document did not say, so it redrew all 12,000 lines of a large log file on every keystroke.

In the push style the subject sends the details with the notification, here a small change event such as { offset: 4180, removed: 0, inserted: "e" }, and the minimap repaints one line. The price is that the event's shape becomes part of the contract with every observer: one that needs a missing field forces a change to the subject, and a field added for one observer travels to all of them. Many designs mix the two, pushing a short description of the change and letting each observer pull the rest.

Every observer runs inside the keystroke

In the simplest form, the one this editor uses, the notify loop calls each observer directly, one after another, on the thread that changed the subject, and setText does not return until the last observer has. Some frameworks queue notifications and deliver them later instead; what follows is about the direct form.

  • A slow observer slows the change. The spell checker rechecked the whole paragraph in every notification, about 80 ms on a long one, so every keystroke spent 80 ms inside setText and typing lagged. An observer with real work to do should note that it is needed, return at once, and do it later, after a pause in typing or off the main thread.
  • A throwing observer can silence the rest. In a plain loop, an exception from the second observer leaves the loop: the third and fourth never hear about the change, and the error surfaces in whatever code called setText. Whether to catch each observer's failure and carry on is the subject author's decision; event libraries that make it for you do not all make the same one.
  • The order is not a contract. Many implementations call observers in the order they subscribed, but the pattern promises no order, and it changes when someone reorders the code that creates them. The reading-time estimate first took its word count from the status bar's counter, which was right only while that counter happened to be notified first. An observer reads what it needs from the subject, not from another observer.

An observer that changes the subject from inside its notification, like a plugin that turns -- into an em dash by calling setText, starts a notification inside a notification, and the observers after it in the outer loop hear about the newer change first: push observers get the two edits out of order, and pull observers are called twice and read the newest text both times. The usual defence is to queue changes made during a round until it has finished; walking a copy of the list is a separate defence, for observers that subscribe or unsubscribe while the loop runs.

The pane that never left

The split view produced one more bug. Each pane's minimap subscribes to the document when the pane opens. A user who opened and closed panes all afternoon found typing getting slower, and a memory snapshot showed 37 minimaps alive with one pane on screen. Closing a pane took it off the window and nothing else: the document's list still held every minimap, and each one still redrew on every keystroke into a canvas nobody could see.

This is the lapsed listener problem. In a garbage-collected language the subject's list is a reference like any other, so an observer that is never unsubscribed stays alive as long as the subject does and keeps being notified. The fix is to make unsubscribing part of the observer's lifecycle; a common shape is a subscribe that returns a handle whose only job is to undo that subscription, which the pane calls when it closes. Weak references, where a runtime offers them, stop the list from keeping an observer alive but bring surprises of their own; without a garbage collector, an observer destroyed without unsubscribing can leave a dangling pointer in the list instead.

No broker in the middle

Later the team wanted two people on different machines to see each other's typing. That is not a job for more observers. In this editor, the subject keeps its observers in its own memory and calls them directly, and whoever registers an observer knows the subject well enough to subscribe it. In publish/subscribe, a publisher usually sends a message to a topic on a broker, which can run in the same process but is often a separate service, and the broker delivers it to whoever subscribed: neither end references the other, and delivery is usually asynchronous. Observer is usually the in-process cousin, the same one-to-many shape without a broker between the ends. A broker in its own service lets the ends live on different machines and one end fail without the other, though both still depend on the broker, at the price of messages that can arrive late, never, or more than once, depending on its guarantees; Publish / Subscribe covers that design.

Observers that start reacting to each other call for a different pattern, Mediator, which also sets out how the two differ.

One more observer

The Observer Pattern Challenge leaves room for six nodes: a subject and its observers, with a subscribe line from each observer to the subject and a notify line back. Judge the drawing the way the editor's team judged their redesign: it is right when it adds a third observer without touching the Subject, the way the reading-time estimate arrived without a change to Document. If a node is left over, an Event for the change details the subject sends with each notification shows push style: it is data on the notify line, not a stop in between.

Practice this