Observer pattern
medium 50 minDecouple 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
Observer
1:01Reel

More reels
One idea each, a minute or less.
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
1979
Trygve Reenskaug formulates model-view-controller at Xerox PARC. Views that follow a model became the classic use of observers.
1994
The book Design Patterns appears and lists Observer among its behavioral patterns.
2000
DOM Level 2 Events becomes a W3C Recommendation on 13 November, with
addEventListener.2001
Python 2.1, released on 17 April, adds weak references, a tool against forgotten observers.
2017
Java 9, available on 21 September, deprecates
java.util.ObservableandObserverand addsFlow, 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.
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 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
1/3The station knows the phone
It calls phone.show. Simple, and fine for one receiver.
uses
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 3Observer
- 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
1/5The subject's promise
Anybody may join, anybody may leave, and all are told.
has (lives on)implements
Set up, notify, leave
The same in four steps
- 1
Register
Observers give the subject a reference to themselves, or a function.
- 2
Change
Something calls a method of the subject, and its state becomes different.
- 3
Notify
The subject goes through its list and calls
updateon each. - 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).
| Push | Pull | |
|---|---|---|
| The call | observer.update(reading) | observer.update(subject) |
| Observer knows | The message type | The subject's getters |
| Data nobody needs | Is sent anyway | Is never asked for |
| Two quick changes | Both values arrive | May see the newest value twice |
| New field in the data | New field in one message type | New getter |
| Across threads or machines | Works, the message is complete | Dangerous: the state may have moved on |
Reading. A new field does not change any signature.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)Which one?
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.
| Question | Usual answer | If you do not decide |
|---|---|---|
| In which order are they told? | No promise, or order of attaching | Somebody 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 more | Skipped observers, or an exception in Java |
| What if one observer raises? | Catch, report, go on | The rest of the list is not told |
| Does attach give the present value? | Say so: some send it at once | A new display stays empty until the next change |
| Is the same value news? | Compare, and stay silent | Useless work, and endless circles |
| On which thread? | The one that changed the state | A window is drawn from the wrong thread |
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, thirdOne 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_measurementssees 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
Neighbours
Observer, pub-sub, mediator, streams
| Who knows whom | Where | Use it for | |
|---|---|---|---|
| Observer | Subject holds its observers through an interface | One process, usually a direct call | State of one object, local |
| Event bus | Both know the bus and the event type | One process | Many senders, many receivers |
| Publish and subscribe | Both know a broker and a topic | Across processes, asynchronous | Other services, must survive a crash |
| Mediator | Colleagues know the mediator, it knows them | One process | Rules between parts that talk to each other |
| Reactive streams | Subscriber asks the publisher for a number of items | One process or a network | Many values over time: filter, join, slow down |
| Webhooks | The sender knows a URL | Across companies | Telling another system by HTTP |
// 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(); // detachesModel and views
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
| Subject | State or event | Observers |
|---|---|---|
| Button in a page | click | validator, analytics |
| Store of a web app (Redux) | state after an action | connected components |
| Stock ticker | price | trading apps |
| Chat room | new message | open windows, notification badge |
| Game | score, level up | display, sound, achievements |
| Sensor | reading | displays, alarm, log |
| Push notification service | new message for an app | registered devices (across a network) |
| Newsletter | new article | readers (by mail, so pub-sub) |
The price
Hidden flow
Reading
set_measurementsdoes not tell you what happens next. Searching forattachdoes.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.