Also known as Dependents or Publish-Subscribe, the Observer pattern helps us create decoupled components and modules. It improves the testability, composition, and scalability of our applications. In this post, I'm going to show you some concepts around the Observer pattern, how it works, and a practical example.
What is Observer?
The authors of the book Design Patterns: Elements of Reusable Object-Oriented Software defines Observer Pattern as:
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
We can think of the Observer pattern as a communication channel between two different modules or objects in order to lose the coupling between them. The observable is an object that notifies observers of changes in its state or a specific property.
An observable can have multiple observers, and these observers are likely to be unrelated to each other and receive update notifications from the observable class. This is usually achieved by calling a callback function provided by each observer. This mode is generally used to implement event processing systems.
How Does It Work?
Initially, we have an Observable class that contains something that other objects are interested in listening to. It can be its state (a composition of multiple properties) or just a single property. In this class, we will have a public subscribe method and a private publishing method to inform observers that something has changed.

Observers will subscribe to the Observable class change of state, passing a callback function. Then, every time the state changes in this subscription, the observers' callback will be called with the new value and other information about the event.
Example
First, we'll define the Listener type and the createObserver function. The createObserver function is responsible for creating observers with subscription and publishing methods.
Next, we'll define our User Observable class that contains a user token listener. We will define userTokenChangedListeners using the createObserver function and it will control the subscription and publication of the user's token changes. So, the public subscription method will receive a callback function from the client and whenever the user's token changes, it will call the publish method on our userTokenChangedListeners property.
Then we can create our Observers that will subscribe to our Observable class using the subscribe method and will receive the user's token updates.
Conclusion
In some situations, you don't want objects to be tightly coupled, for example, when an object must notify other objects, it cannot assume who the other objects are. The Observable pattern is a good solution to solve this kind of problem in a clean architecture.