Igor Simic
1 year ago

How to return boolean from observable using BehaviorSubject


In our previous post  i explained how to return boolean from observable, but in this example i will show you how to make it even more simple by using BehaviourSubject. BehaviourSubject will  emit last value to new subscribers.

So let's start...
let's say we want to hide/show some content based on our observable true/false value. In our HTML component we will have something like this:
<div *ngIf="showThisContent$ | async">

  <p>Test content</p>

</div>

in our test.component.ts we can defined BehaviourSubject, for example, on init event:
showThisContent$;
ngOnInit() {
 this.showThisContent$ = = new BehaviorSubject(false);
}
Our test content inside of HTML will be hidden by default,  but let's say we want to show it when showContent() function is called  - which can be called on button click or some other way. In this function we will assign new value to our BehaviorSubject like this:

showContent(){
  this.showThisContent$.next(true);
}

Now, showThisContent$ have value true, and our "Test content" inside of HTML will become visible.

If you want to use BehaviorSubject value in your code, it is very easy to get last emitted value just by calling method getValue() on your showThisContent$:
this.showThisContent$.getValue()
so for example you can output last emitted value by simple putting it in console.log:
console.log(this.showThisContent$.getValue());

Just for you to know, BehaviorSubject can hold also other types of data: strings, number, arrays, object...

If you want to read more about, check the documentation