Twitter LogoFacebook Logo
BehaviorSubject
BehaviorSubject in Angular
By: King

Hello in this tutorial, we will go over BehaviorSubjects. They are a special type of Observable that we can subscribe to, to get the last value it was set it.


We can use it to add local listeners in our app to listen for a specific change and the perform tasks accordingly.

Syntax

import { BehaviorSubject } from 'rxjs';

...

myBehaviorSubject = new BehaviorSubject<[return_type]>([starting_value]);

Subscribing to Detect Changes

myBehaviorSubject.subscribe(

  (value) => {
      // ... doing something
   }
);

The value parameter represents the new value that it was set last. The anonymous callback function is called every time we make a call to the next() function.

Updating the Value

To trigger the callback function from myBehaviorSubject.subscribe(), grab the BehaviorSubject object and then call the next() function. Inside the function, pass in the new value you want it to return.

myBehaviorSubject.next([some_value]);

Example

gameEndedListener = new BehaviorSubject<Boolean>(false);


gameEndedListener .subscribe(
  (ended) => {
      if(ended){
          console.log("The game has ended");
      }
   }
);

gameEndedListener.next(true);

In the example, there is a listener call gameEndedListener that listens for a change in the Boolean value that was passed in.


In the last line, we used the next() function to update the value to true and it will trigger the callback function from the subscribe() function. From there, it checks if the value that was passed in (ended) is true. If it is, it will print out a message.


Sign In