Skip to main content

How to use Observer Service

The src/services/ObserverService.ts is a basic implementation of the Observer design pattern. It is can be used to notify one component that some other data on a different part was changed and to reflect the change in the first component.

This class is helpful when some settings were changed in one part of the application while the other parts are still using the old data. So to solve this problem and not use props drilling or contexts we use this class instead.

How to use

We make use of the observe method to observe, the notify method to notify the listeners and we maintain a Topics class to list all the topics.

Register an observer

To use this, you will need an observer that waits for the notification and a notifier.

Register an observer using the observe method and send a topic name as the first parameter and a callback function as the second parameter. When a notifier notifies this topic then the callback method will be executed.

There is an exported global observer variable in the ObserverService. Call this observe method on this variable.

observer.observe(
Topics.settings,
()=>{
getNewSettings();
}
);

Notify the observer

In the exported global observer variable in the ObserverService. Call this notify method on this variable.

observer.notify(Topics.settings);