The Observer Pattern
TL;DR; “Call me when something I care about occurs”.
The Problem occurs when a client cares about a particular event.
For Example, if a movie store has a particular movie ready for rent.
The client might solve this by repeatedly checking the movie store. Making many trips, and mostly
unsuccessful until the movie is in stock.
The Movie Store might solve this by calling the client every time a movie gets returned. But this
is annoying and also wastes a lot of effort. (It’s SPAM!)
A Better solution might be for the movie store to keep track of customers who are interested in a
particular movie. That way the only communication that occurs is communication that is valuable.
For this example we’ll use the status of a network call. Let’s say it has 3 possible states…
For this example we don’t care what we would like to do during these states, that’s up to larger
There are two members in the observer pattern…
the Subject - the one being observed
the Observer - the one who is observing
sometimes referred to by different names.
it works by the subject having a
.subscribe(Observer observer) that takes in an observer.
.subscribe(Observer observer) is called, the Subject adds the Observer to some kind of collection it is tracking – basically a list of who to call when an event happens.
but what to call?
there will be something analogous to an
.update(...) method on the observer class that the Subject will know to call with relevant updates.
The code does not have to read exactly the same to be using a particular pattern
in this example, I’m be using the method
on(event: EventName, handler: Function) instead of the more
and in place of the standard
.update(...) method, I’m using regular old functions, since JS supports first class functions.
but it’s the same idea. “Call me when something I care about occurs”.
A test might look like…
Thanks for the read.