Observer pattern in swift


In iOS programming, we all have come across the term KVO which is key-value observer and if you have worked in an MVVM project then you might have used libraries like RxSwift.
However, KVO and RxSwift both work on the same principles which is the observer design pattern and hence it is very important to understand what this design pattern is and how it works
The observer design pattern consists of two components
1. Subject
2. Observer
To understand what is a “Subject” and “Observer” I would like to give an example

When the traffic lights are red, we stop the vehicle and observe the lights and wait for it to turn green
Once the traffic lights turn green we accelerate the vehicle and proceed to our destination.
Here the observer are the people who are waiting for the signal to turn green, when the signal turns green they act accordingly.
The subject, in this case, is the traffic light because when it’s state changes i.e. the color of the traffic light the observers who are observing the state of the traffic light act accordingly.
The subject maintains a list of observers and when it’s state changes it sends a notification to all the observers who have subscribed to that state change.
If we want to look how this would look from a code perspective then here’s how we can code the same in swift
Let’s start by creating a protocol with basic functionality that can be used by anyone who wants to observe the traffic light.
Do note that while in traffic, the people in the vehicle observe the light and along with them there are few other folks like people who cross the road and vendors who sell their products they too observe the same light and act accordingly.
For a vendor when the lights are red it’s an indication that he has to sell his products whereas for the people crossing the road it’s an indication that they have to walk.
And hence we need a protocol here so that these observers can have the same function with different functionality

I will explain why we need an Id as we progress with the session
Now that’s in place let’s create the Vehicle and Vendor observer which will inherit the “ObserverProtocol”
Vehicle Observer

The vehicle observer is pretty simple and it acts based on the color that’s passed as a parameter.
The “TrafficColor” is a structure with static properties

Vendor Observer:

The vendor observer here acts differently from the vehicle observer as you can see when the lights are red, the vendor starts to sell the products whereas when the lights are green the vendor moves aside from the traffic
Now it’s time to create the subject, which is the TrafficLightSubject

I have added code comments so that it becomes easy to understand what each function is doing but in general here’s what’s happening
We have a public property called trafficLightColor which will be used to change the color of the traffic light, when a new color is assigned inside the set method we will call a function named notifyObserver.
The notifyObserver will trigger the “onTrafficLightColorChange” function of all the observers which are added in the array named “trafficObserver”
We have an “addObserver” function that accepts the ObserverProtocol as a parameter, and before adding any observer in the array we have a guard statement to check if this observer was already added in the array to avoid duplicates.
Note: The Id is used to give each object a unique id which helps to identify in the addObserver method whether this object was already added in the “trafficObserver” array
It’s a good idea to add one more function which is “removeObserver” to remove any observes which we want to remove

Note: Again we are using the Id property here to remove the observer from the array
As a good coding practice, we will use the deinit statement to remove all the objects from the “trafficObserver” array.



Now let’s create some objects and see how this goes

As you can see at line 114 and 115 we are adding the object of Vehicle and Vendor observer to the trafficObserver array using the addObserver function
And in line 117 when we change the color of the trafficLight to green then in the console you can see two different objects behaving differently based on the state of the traffic light
The same behavior can be observed when we change the traffic light from green to red

This is how the observer pattern works in general and I hope after reading this article you have a basic understanding of this design pattern.
I have released a YouTube video on this topic on my channel, do check that out. It’s in Hindi language and I am working on uploading the subtitles soon.
Do subscribe to the channel and share it with your iOS group





Thank you so much for your time, Have a nice day and happy iCoding.

Comments

  1. Having read your article. I appreciate you are taking the time and the effort for putting this useful information together.

    BSc Part 2 Time Table

    ReplyDelete
  2. Having read your article. I appreciate you are taking the time and the effort for putting this useful information together.
    bsc 2nd year result 2021 name wise

    ReplyDelete
  3. The information you have produced is so good and helpful, I will visit your website regularly.

    ReplyDelete
  4. I got such a useful stuff on your website that helps me a lot to gain information.

    ReplyDelete

Post a Comment