AlgoViz

Observer pattern

medium 50 min

Decouple a state-holding subject from its dependents: they register, and the subject notifies everyone on its list when something changes.

Chapter mnemonic

Observer notification lifecycle

Sign up. News breaks. Papers arrive. Cancel delivery.

Someone cancels the paper. What relationship must the publisher update?

Remove the subscription so future changes no longer notify that observer.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:58

Observer

1:01Reel

Observer pattern in one picture
Observer pattern in one picture

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Observer vs mediator

0:32Reel

Theory

Read or listen first. About 2 min.

What it is

Observer is a behavioral design pattern for a one-to-many dependency. One object, the subject, has state or produces events. Others, the observers, register with it and are called when something happens.

The subject knows only a small interface, or a function type. It does not know the classes behind it, how many there are, or what they do.

Registration happens at run time. Observers join and leave while the program works.

Why it exists

When one part changes its state, several others often need to react. If the part calls each of them directly, it depends on all of them, must be edited for each new one, and can not be tested alone.

Observer turns these dependencies around. The receivers depend on the subject's message, and new receivers need no change in the subject: it is open for extension and closed for modification, see open-closed principle.

It replaces polling. Nobody asks in vain, and nobody learns the news late.

The price is that control flow becomes invisible. So the rules of a round must be decided and written down: order, errors, joining and leaving, threads, and the end of a subscription.

A short history

  1. 1979

    Trygve Reenskaug formulates model-view-controller at Xerox PARC. Views that follow a model became the classic use of observers.

  2. 1994

    The book Design Patterns appears and lists Observer among its behavioral patterns.

  3. 2000

    DOM Level 2 Events becomes a W3C Recommendation on 13 November, with addEventListener.

  4. 2001

    Python 2.1, released on 17 April, adds weak references, a tool against forgotten observers.

  5. 2017

    Java 9, available on 21 September, deprecates java.util.Observable and Observer and adds Flow, interfaces for streams in which the receiver says how much it can take.

Words to know

Subject
The object that is observed. It keeps the list.
Observer
Who is told. Listener, subscriber and watcher mean the same.
Round
One pass through the list for one change.
Push
The data travels with the call.
Pull
The call says that something changed, observers ask for the rest.
Subscription
The link between an observer and a subject, and the handle that ends it.
Lapsed listener
An observer nobody needs any more, kept alive by the subject's list.
Reentrancy
A round that starts inside another round.
Glitch
An observer sees a mixture of new and old values for a moment.
Backpressure
A slow receiver tells the sender how much it can take.
Coalescing
Several changes become one notification.
Hollywood principle
Do not call us, we will call you.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Register. Observers register their callback or interface reference with the subject.

Understand it

Start here

Do not ask again and again

Something changes, and several others want to know. They could ask every minute. Or the thing that changes could know each of them by name. The Observer pattern does neither. Whoever is interested signs up, and the thing that changes tells everybody on its list.

The hen and the strings
HENNoorLeeSamNo egg?

The hen does not call Noor, Lee or Sam. It pulls whatever is tied.

Four participants

  • Subject

    Also called observable. Keeps the list: attach, detach, notify. Knows only the Observer interface.

  • Observer

    An interface with one method, update. Subscriber, listener and watcher are other names.

  • Concrete subject

    Holds the state and notifies when it changes: a weather station, a stock, a news channel, a button.

  • Concrete observer

    Reacts in its own way: a phone display, an investor app, an email client, a click handler.

Two everyday pictures

  • A video channel

    You subscribe. A new video appears, and you and all other subscribers get a notice. Nobody looks at the channel every hour.

  • A newsletter

    Readers sign up, an article is sent to all of them, and each can leave without telling the others.

Why

What goes wrong without it

A weather station measures. A phone and a web page show the values, and somebody wants a mail when it gets hot. The first version calls all three.

The design that hurts

WeatherStation- phone: PhoneDisplay- web: WebDashboard- mail: EmailAlert+ setMeasurements()PhoneDisplay+ show(temp, hum)

1/3The station knows the phone

It calls phone.show. Simple, and fine for one receiver.

uses

The arrows point from the stable part to the parts that change most. They should point the other way.
Python
values = [20, 20, 20, 35, 20, 20, 20, 24, 24, 24, 24]   # one per secondseen, questions, last = [], 0, Nonefor second in range(0, len(values), 2):   # ask every 2 seconds    questions += 1    if values[second] != last:        last = values[second]        seen.append(last)changes = sum(a != b for a, b in zip(values, values[1:]))print("asked", questions, "saw", seen)    # asked 6 saw [20, 24]print("real changes", changes)            # real changes 3
The other naive way, polling. Run it: six questions, two values seen, and the jump to 35 is missed.
Edit and run it in your browser

Observer

  • The subject knows one small interface
  • A new receiver is a new class and one attach
  • Attach and detach while the program runs
  • News arrives when it happens

Direct calls or polling

  • The subject imports every receiver
  • A new receiver edits the subject
  • Receivers can not come and go at run time
  • Polling is late, wasteful, or both

The idea

A list of people who asked

The Observer pattern in general

«interface»Subject+ attach(o: Observer)+ detach(o: Observer)+ notifyObservers()

1/5The subject's promise

Anybody may join, anybody may leave, and all are told.

has (lives on)implements

Put the list into a base class or into a small helper object that the station owns. Both are Observer.

Set up, notify, leave

The calls happen one after another, not at the same time. The second update starts when the first returned.

The same in four steps

  1. 1

    Register

    Observers give the subject a reference to themselves, or a function.

  2. 2

    Change

    Something calls a method of the subject, and its state becomes different.

  3. 3

    Notify

    The subject goes through its list and calls update on each.

  4. 4

    React

    Each observer does its own work, or ignores the news.

Data

Push or pull

How does the news reach the observer? The subject can send the data with the call (push). Or it can say only that something changed, and the observers ask for what they need (pull).

PushPull
The callobserver.update(reading)observer.update(subject)
Observer knowsThe message typeThe subject's getters
Data nobody needsIs sent anywayIs never asked for
Two quick changesBoth values arriveMay see the newest value twice
New field in the dataNew field in one message typeNew getter
Across threads or machinesWorks, the message is completeDangerous: the state may have moved on
Good middle way: push one immutable object, such as Reading. A new field does not change any signature.
Python
class Station:    def __init__(self):        self.push_observers, self.pull_observers = [], []        self.temperature = self.humidity = 0    def set(self, t, h):        self.temperature, self.humidity = t, h        for o in list(self.push_observers):            o(t, h)                         # push: here is the data        for o in list(self.pull_observers):            o(self)                         # pull: ask mes = Station()s.push_observers.append(lambda t, h: print("push", t, h))s.pull_observers.append(lambda subject: print("pull", subject.temperature))s.set(21, 60)
Both in one file. The pull observer does not mention humidity at all.
Edit and run it in your browser

Which one?

When in doubt, push a small immutable object.

Fine print

Four promises to decide

The pattern in the book is ten lines. The behaviour in a real program depends on questions that those ten lines answer by accident.

QuestionUsual answerIf you do not decide
In which order are they told?No promise, or order of attachingSomebody starts to rely on it
May an observer attach or detach during a round?Yes: go through a copy. Who left is not called any moreSkipped observers, or an exception in Java
What if one observer raises?Catch, report, go onThe rest of the list is not told
Does attach give the present value?Say so: some send it at onceA new display stays empty until the next change
Is the same value news?Compare, and stay silentUseless work, and endless circles
On which thread?The one that changed the stateA window is drawn from the wrong thread
Python
class Subject:    def __init__(self):        self.observers = []    def notify(self):        for o in self.observers:             # not a copy            o()s = Subject()def once():    print("once")    s.observers.remove(once)s.observers += [once, lambda: print("skipped"), lambda: print("third")]s.notify()                                   # once, third
Removing while looping. Python does not complain: it skips the neighbour. Run it.
Edit and run it in your browser

One of 50 observers raises an exception in update. What should the subject do?

BreaksNothing special
How
The exception leaves the loop.
Limit
Those behind it are never told, and the caller of set_measurements sees an error of a display it does not know.
Choose when
Never by accident.
WorksCatch and ignore
How
except Exception: pass.
Limit
A broken observer looks healthy for months.
Choose when
Never alone.
StrongCatch each, report, go on
How
Hand the error to a handler that logs and counts. After several in a row, remove the observer and say so.
Limit
The caller does not learn about failures. If it must, the thing is not an observer but a step of the operation.
Choose when
The default.

The life of a subscription

Every subscription needs a way to the end. If you can not say who detaches, you have a leak.

Neighbours

Observer, pub-sub, mediator, streams

Who knows whomWhereUse it for
ObserverSubject holds its observers through an interfaceOne process, usually a direct callState of one object, local
Event busBoth know the bus and the event typeOne processMany senders, many receivers
Publish and subscribeBoth know a broker and a topicAcross processes, asynchronousOther services, must survive a crash
MediatorColleagues know the mediator, it knows themOne processRules between parts that talk to each other
Reactive streamsSubscriber asks the publisher for a number of itemsOne process or a networkMany values over time: filter, join, slow down
WebhooksThe sender knows a URLAcross companiesTelling another system by HTTP
A message broker is not a bigger Observer. It adds storage, delivery rules and operations work. Use an interface when an interface is enough.
TypeScript
// bus: neither side knows the otherbus.subscribe("user:login", (user) => greet(user));bus.publish("user:login", { name: "Asha" });// stream: values over time, with operators in betweenprice$  .pipe(filter((p) => p > 100), debounceTime(500))  .subscribe((p) => alert("High: " + p));fromEvent<MouseEvent>(button, "click")  .pipe(throttleTime(1000), map((e) => e.clientX))  .subscribe((x) => console.log("clicked at", x));// browser: the button is the subjectbutton.addEventListener("click", onClick, { signal: controller.signal });controller.abort(); // detaches
The same idea three times. An event bus, a stream with operators (RxJS), and the browser.

Model and views

Model-view-controller keeps several views of one model in step: the model is the subject, the views observe it.

Choosing

When to use it and when not

Use it when

  • A change in one object concerns several others
  • You do not know who they will be
  • Receivers come and go at run time
  • Each reaction is independent of the others
  • You build models and views, live feeds, events

Leave it when

  • Exactly one receiver is known: call it
  • Reactions must happen in a fixed order: write the steps down
  • The caller needs to know whether they worked
  • Observers change each other in a circle
  • Thousands of updates per second hit slow observers

Where you meet it

SubjectState or eventObservers
Button in a pageclickvalidator, analytics
Store of a web app (Redux)state after an actionconnected components
Stock tickerpricetrading apps
Chat roomnew messageopen windows, notification badge
Gamescore, level updisplay, sound, achievements
Sensorreadingdisplays, alarm, log
Push notification servicenew message for an appregistered devices (across a network)
Newsletternew articlereaders (by mail, so pub-sub)

The price

  • Hidden flow

    Reading set_measurements does not tell you what happens next. Searching for attach does.

  • Update storms

    One change starts three, which start nine.

  • Leaks

    Who never detaches lives for ever.

  • Slow neighbours

    The calls are in a row. One slow observer delays the subject and all others.

Summary

The whole topic in one minute.

One subject, many observers, one small interface. Store the new state, go through a copy of the list, skip who left, catch and report errors. Push an immutable message unless observers need very different parts.

A subscription is a resource: attach returns a handle, an owner closes it. If observers may publish, queue events so that all see one order.

With threads: copy on write, no lock during calls, bounded queues with a rule for slow observers. Tell facts after the commit. Between processes it becomes pub-sub, and the promises change.

  • One subject, many observers, one small interface between them.
  • The subject notifies itself after a change, so no caller can forget it.
  • Push one immutable object, unless observers need very different parts.
  • Go through a copy of the list, skip who left, catch each error, report it.
  • Attach returns something that detaches. Tie it to the owner's life.
  • In one process it is Observer. With a broker between, it is pub-sub, with other promises.

Sources