Observer Pattern
In this article, we will have a look at the observer pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state or data changes, usually by calling one of the method of observers (From Wikipedia).
In simpler words, the Observer pattern defines,
- Subject (provider) that is responsible for monitoring and updating some sort of data and sending the notification to the observers
- Observer that receives notification from Subject (provider).
- Low level of loose coupling between Subject and Observers by defining Subject and Observers in such a way that none of them have any explicit knowledge of each other but Subject maintains a list of Observers.
- Subject (provider) provides Observers a method to subscribe (attach) and unsubscribe (detach) themselves.
- A One-To-Many relationship between Subject (provider) and Observer which means a subject can have multiple dependents (observers) who want to get notified when change happens in the subject state, for example, a library named “TemperatureCalculatorLibrary” (Subject) which computes temperature can have many dependents applications (Observers) who need the updated temperature data for displaying or further calculation or predictions.
- A solution for push-based notification where Subject provides Observers the updated data or notifies all the observers by calling one of their methods whenever there is any change happens to the subject’s state or data - there is no way that observers themselves update or get the data from a subject.
Now, let’s have a look at the general implementation to understand the Observer pattern in a more detailed way.
Define an interface named “IObserver” that contains a property to store a name of the observer object and differentiate two objects from each other. A method named “UpdateObserver” that is being called by the Subject to notify the observer object and this is the method which almost every observer class would have.
- public interface IObserver
- {
- string ObserverName { get; set; }
- void UpdateObserver();
- }
Let’s have a look at the implementation of "Subject" that maintains a list of "Observers". Since every Subject would have somewhat these methods, I tied those in an interface. The Subscribe-Unsubscribe method is the ones through which the Observers register-unregister themselves to the Subject. The “NotifyObservers” method is the one which has the responsibility of notifying all the Observers. We have added a property “SubjectState” to determine or hold the current state of the subject and the “ModifySubjectStateOrData” method is the one which is defined to modify the current state,
- public class Subject
- {
- private readonly List<IObserver> _observers = new List<IObserver>();
-
- public string SubjectName { get; set; }
-
- public Subject(string subjectName)
- {
- SubjectName = subjectName;
- SubjectState = "Created";
- Console.WriteLine("Instantiated named Subject {0}", SubjectName);
- }
-
- public string SubjectState { get; set; }
-
- public void Subscribe(IObserver observer)
- {
- _observers.Add(observer);
- Console.WriteLine("Observer named {0} is now added to the {1}'s observers list and will receive notification when change happens to the subject {1} state", observer.ObserverName, SubjectName);
- }
-
- public void Unsubscribe(IObserver observer)
- {
- _observers.Remove(observer);
- Console.WriteLine("Observer named {0} is removed from the {1}'s observers list and will no longer receive notification when change happens to the subject {1} state", observer.ObserverName, SubjectName);
- }
-
- public void NotifyObservers()
- {
- foreach (IObserver observer in _observers)
- {
- observer.UpdateObserver();
- }
- }
-
- public void ModifySubjectStateOrData(string subjectStateOrData)
- {
- Console.WriteLine("{0} state changed from {1} to {2}", SubjectName, SubjectState, subjectStateOrData);
- SubjectState = subjectStateOrData;
- NotifyObservers();
- }
- }
Let’s have a look at the implementation of "Observer" that implements interface “IObserver”,
- public class Observer : IObserver
-
- private Subject _subject;
- public Observer(string observerName)
- {
- ObserverName = observerName;
- }
-
- public string ObserverName { get; set; }
-
- public void Subscribe(Subject subject)
- {
- _subject = subject;
- subject.Subscribe(this);
- }
-
- public void Unsubscribe()
- {
- _subject.Unsubscribe(this);
- }
-
- public void UpdateObserver()
- {
- Console.WriteLine("{0} received the notification", ObserverName);
- }
Let’s look at the main method which would complete our code for using the Observer pattern.
- static void Main(string[] args)
- {
- Subject S1 = new Subject("S1");
- Observer O1 = new Observer("O1");
- Observer O2 = new Observer("O2");
-
- O1.Subscribe(S1);
- O2.Subscribe(S1);
- S1.ModifySubjectStateOrData("Approved");
- Console.WriteLine();
-
- O2.Unsubscribe();
- S1.ModifySubjectStateOrData("Implemented");
-
- Console.ReadLine();
- }
Within the Main method, we create an instance of Subject that we can subscribe/unsubscribe different observers. When the State in the Subject changes, we notify the Observers by their Update method (look at the code in Subject class).
As we look at the above implementation we can see that Observer and Subject know about each other, which means to some extent they are coupled (not completely loosely coupled). To overcome this problem, .NET Framework provides a generic System.IObservable<T> and System.IObserver<T> interfaces which can be implemented by Subject and Observer to apply Observer pattern.
As mentioned earlier, the observer design pattern is suitable for distributed push-based notifications and requires
- · A provider to send notifications to observers.
- · An observer that receives notifications from a provider.
Implement a Provider using a generic System.IObservable<T> interface
Define a provider class that implements the System.IObservable<T> interface where T is the type of data that the provider sends to an observer.
- The Provider class implements the single method “Subscribe” which provides an ability to an observer to register themselves with the Subject (provider). The “Subscribe” method stores a reference to the observer in a collection object, such as a List<T> object and returns a reference to an IDisposable interface that enables observers to unsubscribe (that is, to stop receiving notifications).
- The provider class implements a method that is responsible for notifying the observers by calling any one of the Observer method IObserver<T>.OnNext, IObserver<T>.OnError, and IObserver<T>.OnCompleted implemented.
Implement an Observer using generic System.IObserver<T> interface
Define the observer class that implements the System.IObservable<T> interface where T is the type of data that observer received from the provider,
- Defines a Subscribe method that calls the provider's Subscribe method and passes a reference of Observer instance
- Define a private variable that will hold the IDisposable implementation returned by the provider's IObservable<T>.Subscribe method
- Defines an Unsubscribe method that calls the Dispose method on the IDisposable object
- Provide implementations of the three methods defined by the IObserver<T> interface: IObserver<T>.OnNext, IObserver<T>.OnError, and IObserver<T>.OnCompleted.
Points to Remember
- The provider and observer may both try to remove the same member from the Observers list so both the Subscribe and Dispose of methods should be thread-safe.
- We should avoid an attempt to unregister in the IObservable<T>.Subscribe method because it may result in a null reference.
- Although it is possible to attach an observer to multiple providers, the recommended pattern is to attach an IObserver<T> instance to only one IObservable<T> instance.
- The observer should not throw exceptions from its interface implementations, such as OnNext or OnError.
Now, let’s have a look at the real-world example to understand the Observer pattern .Net Framework implementation in a more detailed way,
Problem Statement
Suppose we have a video player which is responsible for playing video and keeping live video status, for example, how much time has already elapsed, how much video time is remaining, what percentage of the video is completed. Now, whenever video time elapsed changes by 10 minutes or video completed percentage exceeds 10 percent, all the observer GUI platforms must be notified so that respective GUIs can display current video live status.
The following example contains the complete source code for defining an IObservable<T> implementation for a Video Player monitoring application. It includes the VideoStatus structure, which is the data sent to observers, and the VideoStatusPercentageMonitor, VideoStatusMonitor, VideoStatusTimeMonitor - which are the IObserver<T> implementation.
Let’s have a look at the IObservable<T> implementation class named “VideoPlayer” – this class defines three methods to Start, Pause and Stop Video. A method named “GetVideoStatus” executing in a separate thread is initiated to update the current state in the data structure object i.e., VideoStatus,
Let’s have a look at the IObserver<T> implementation class named “VideoStatusPercentageMonitor”, “VideoStatusMonitor”, “VideoStatusTimeMonitor” – this implements the method IObserver<T>.OnNext and updates the status based on the data object VideoStatus received from the Publisher (provider).
- public class VideoStatusMonitor : IObserver<VideoStatus>
- {
- private IDisposable _unsubscriber;
-
- public virtual void Subscribe(IObservable<VideoStatus> provider)
- {
- _unsubscriber = provider.Subscribe(this);
- }
-
- public virtual void Unsubscribe()
- {
- _unsubscriber.Dispose();
- }
-
- public void OnCompleted()
- {
- }
-
- public void OnError(Exception error)
- {
- }
-
- public virtual void OnNext(VideoStatus value)
- {
- Console.WriteLine("------------------------------------------------");
- Console.WriteLine("Video is currently {0} ", value.Status.ToString());
- }
- }
-
- public class VideoStatusTimeMonitor: IObserver<VideoStatus>
- {
- private IDisposable _unsubscriber;
-
- public virtual void Subscribe(IObservable<VideoStatus> provider)
- {
- _unsubscriber = provider.Subscribe(this);
- }
-
- public virtual void Unsubscribe()
- {
- _unsubscriber.Dispose();
- }
-
- public void OnCompleted()
- {
- }
-
- public void OnError(Exception error)
- {
- }
-
- public virtual void OnNext(VideoStatus value)
- {
- var ts = TimeSpan.FromSeconds(value.TimeElapsed);
- var format = $"H: {ts.Hours} M:{ts.Minutes} S:{ts.Seconds}";
-
- var timeremaining = TimeSpan.FromSeconds(value.TimeRemaining);
- var timeremainingformat = $"H: {timeremaining.Hours} M:{timeremaining.Minutes} S:{timeremaining.Seconds}";
-
- Console.WriteLine();
- Console.WriteLine("Video Player Time Monitor");
- Console.WriteLine("Time {0} elapsed : Remaining {1}", format, timeremainingformat);
- }
- }
-
- public class VideoStatusPercentageMonitor : IObserver<VideoStatus>
- {
- private IDisposable _unsubscriber;
-
- public virtual void Subscribe(IObservable<VideoStatus> provider)
- {
- _unsubscriber = provider.Subscribe(this);
- }
-
- public virtual void Unsubscribe()
- {
- _unsubscriber.Dispose();
- }
-
- public void OnCompleted()
- {
- }
-
- public void OnError(Exception error)
- {
- }
-
- public virtual void OnNext(VideoStatus value)
- {
- Console.WriteLine();
- Console.WriteLine("Video Player Percentage Monitor");
- Console.WriteLine("Video {0} % completed ", value.VideoCompletedPercentage);
- }
- }
Let’s have a look at the Main method implementation which completes our observer pattern implementation – we have created an instance of VideoPlayer class and created an instance of three different VideoStatusMonitors; i.e., “VideoStatusPercentageMonitor”, “VideoStatusMonitor”, “VideoStatusTimeMonitor”. Finally, we attached these observers (monitors) with the VideoPlayer to get notified whenever Video Status changes. After all these initializations, we have called a method as below,
- “StartVideo” to start video which also initiates a separate thread to update the current status of Video
- Wait for around 2 seconds then call method “PauseVideo” to pause the video
- Wait for around 2 seconds then call method “StartVideo” to re-start the video
- Wait for around 3 seconds then call method “StopVideo” to finally stop the video
Please note that during this process VideoStatusMonitor will keep displaying the current i.e., “Running”, “Paused”, or “Stopped” state, VideoStatusTimeMonitor will keep displaying Video Time Elapsed and Video Time Remaining and VideoStatusPercentageMonitor will keep displaying the Video completed in percentage based on the data received from the provider (IObservable implementation).
- static void Main(string[] args)
- {
- VideoPlayer videoPlayer = new VideoPlayer(360);
-
- VideoStatusMonitor videoStatusMonitor = new VideoStatusMonitor();
- videoStatusMonitor.Subscribe(videoPlayer);
-
- VideoStatusTimeMonitor videoStatusTimeMonitor = new VideoStatusTimeMonitor();
- videoStatusTimeMonitor.Subscribe(videoPlayer);
-
- VideoStatusPercentageMonitor videoStatusPercentageMonitor = new VideoStatusPercentageMonitor();
- videoStatusPercentageMonitor.Subscribe(videoPlayer);
-
- videoPlayer.StartVideo();
- Thread.Sleep(2000);
- videoPlayer.PauseVideo();
- Thread.Sleep(2000);
- videoPlayer.StartVideo();
- Thread.Sleep(3000);
- videoPlayer.StopVideo();
-
- Console.ReadLine();
- }
Output
Summary
- The Observer design pattern defines an observer, which registers for notifications, and a subject (provider), which monitors data and sends notifications to one or more observers.
- The Observer design pattern is suitable for distributed push-based notifications.
- The Observer pattern is mostly implemented in a synchronous way, i.e. the Subject calls the appropriate method of all its observers when some event occurs.
- The Observer Pattern is the foundation of the Model View Controller (MVC) pattern, in which a view is updated automatically whenever the model's state changes.
- The Observer Pattern a one-to-many relationship between two objects that allows one or many observed objects to be updated by the subject object.