Observer Pattern: How does it work?

Android developers these days are overzealous about Reactive programming or RX programming. Rx programming is all they talk about!

As per the ReactiveX project, “ReactiveX is a combination of the best ideas from the Observer pattern, the Iterator pattern, and functional programming.”

You must be using Rx libraries inside your projects. But what is the magic behind Observers and Observables? How do they work under the hood? (Interview Question Alert!)

Definition of Observer Pattern

The Observer Pattern defines a one to many dependencies between objects so that one object changes state, all of its dependents are notified and updated automatically.

If this is not simple enough then let’s think about a real-world example :
You have subscribed to a website(Subject) and it notifies you(Observer) via email about a new post that is published on their website.

In technical terms, It has a subject — which causes the change, and observers — which performs some action after the change has occurred.

So enough about the description and terminology. Lets code:

public interface BaseSubject {
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyObservers();
}

Here is our BaseSubject interface. Every Observable must implement this interface to register the Observers inside it. So that on state change, it can notify all the Observers. Whenever Observers simply want to unsubscribe themselves, they can remove themselves from the subscription.

But wait, where does the Observer come from?

public interface Observer {
void update(String post);
}

Whenever the Subject has a new Post, it will simply notify the Observer via update() method.

Here is our WebsiteSubject which implements our BaseSubject:

public class WebsiteSubject implements BaseSubject {

private ArrayList<Observer> observers;

private String post;

public WebsiteSubject() {
observers = new ArrayList<>();
}

public void setData(String post) {
this.post = post;
notifyObservers();
}

@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}

@Override
public void removeObserver(Observer observer) {
observers.remove(observers.indexOf(observer));
}

@Override
public void notifyObservers() {
for (Observer observer :
observers) {
observer.update(post);
}
}

WebsiteSubject is the Observable in this case, which simply maintains the ArrayList of Observers. Whenever there is a new post, it notifies each observer which is subscribed to this Observable.

Now Let’s write Observers which will listen to those updates:

public class UserInterface implements Observer {
private WebsiteSubject websiteSubject;
private String post;

public UserInterface(WebsiteSubject websiteSubject) {
this.websiteSubject = websiteSubject;
}

private void display() {
System.out.println("UserInterface : New Post " + post);
}

@Override
public void update(String post) {
this.post = post;
display();
}
}
public class Logger implements Observer {
private WebsiteSubject websiteSubject;

private String post;

public Logger(WebsiteSubject websiteSubject) {
this.websiteSubject = websiteSubject;
}

private void log() {
System.out.println("Logger : New post " + post);
}

@Override
public void update(String post) {
this.post = post;
log();
}
}

Let’s check our implementation :

public class ObserverPattern {

public static void main(String[] args) {
WebsiteSubject websiteSubject = new WebsiteSubject();

UserInterface ui = new UserInterface(websiteSubject);
websiteSubject.registerObserver(ui);

Logger logger = new Logger(websiteSubject);
websiteSubject.registerObserver(logger);

websiteSubject.setData("Post 1");

websiteSubject.removeObserver(logger);

websiteSubject.setData("Post 2");
}
}

First, we registered the UserInterface and Logger to WebsiteSubject. When the new post is published on the website, both the observers listened to it and displayed it in the output. Then Logger unregisters itself from the new post. When the next post is published, UserInterface is the only observer remaining and it got notified.

Android Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store