Hi everyone, in this post, I will share my experience on how to create a custom event service in Angular using **observables **which is based on the principle of observer pattern and is **similar **to the principle of publish/subscribe design pattern.
In observer pattern, an object known as **subject **maintains a record of its dependents known as observers and informs them implicitly whenever there is a state change. Whereas in publish/subscribe design pattern, senders of the messages known as publishers do not send the messages directly to the specific receivers known as subscribers, instead communicate with each other through an **agent **known as **broker **or **message broker **or **event **bus.
In this example, I have created a custom message event service and I will show you how it is being used by other angular components.
Below is the code snippet of the custom message event service file.
message.event.service.ts
In this file, I have created a class called “MessageEventManager” which uses the Observable, **Observer, **and **Subscription **class of **RxJS **library and are the building blocks of our custom message event.
As shown in the code snippet, we have created a **constructor **and **initialized **the class members inside it and is **called **whenever a new **object **is created.
The share() operator inside the constructor is used to **rebuild **a new subject and subscribe it to the source observables whenever a subscription is made after the reference count drops to zero.
The **subscribe(eventName: any, callback:any) **method is used to register the eventName and return the **subscriber **and the **broadcast(event:any)**method is used to broadcast the next event.
The destroy(subscriber:Subscription) method is used to **unsubscribe **the subscriber. This method prevents memory leakage and is recommended as one of the best practices.
Next, we have created a simple app component in angular which uses MessageEventManager class to describe how message event service is used while triggering a demo event from app service.
#observer-pattern #observer-design-pattern #angular #observables