Behaviour Subject in Angular - Implementation


 

What is the behavior subject?

Behavior subject is a type of observable in angular to which we can subscribe to and get the value changes on the behavior subject immediately in the method where we subscribed. So whenever the data of variable declared in the type of a particular behavior subject changes the same data change will be notified in the method where the particular behavior subject is subscribed.

When to use behavior subjects?

when we need to communicate between components and the same communication is repetitive between many components. In such scenarios we can use behavior subjects as a centralized/single observable among all these components.for example: suppose we need a common loader in the application and the same needs to be called from all the components or services.in such cases, we can utilize a behavior subject and write a common method that subscribes that behavior subject to monitor calls for showing / hiding the loader.

Advantages of using behavior subject?

  1. Access data without bothering the timing
  2. Keep data updated throughout the application
  3. managed intercommunication between components

Stages of implementations

 Reference Links

Declaring & Assigning values to a behavior subject in service :


  public ShowLoader = new BehaviorSubject<boolean>(false);

  InvokeLoader(Showboolean) {
    this.ShowLoader.next(Show);
  }

Listnening to all changes happening to the behaviour subject :

  this.dataservice.ShowLoader.subscribe((show=> {
      this.ShowLoader = show;
    });


https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc

https://www.joshmorony.com/using-behaviorsubject-to-handle-asynchronous-loading-in-ionic/

Comments