loading...
Cover image for Little example on how to use BehaviorSubject (Observable) in angular

Little example on how to use BehaviorSubject (Observable) in angular

sabrinasuarezarrieta profile image sabrinasuarezarrieta ・1 min read

Today I had to implement an observable in one project in angular, and I found that BehaviorSubject was the best option, so first let's define BehaviorSubject, is a type of subject, a subject is a special type of observable (is a producer of multiple values, "pushing" them to observers or consumers who are subscribed to that producer) so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:

  • It needs an initial value as it must always return a value on subscription even if it hasn't received a next()
  • Upon subscription, it returns the last value of the subject.
  • At any point, you can retrieve the last value of the subject in a non-observable code using the getValue() method.

With that in mind lets go to see the little example.

componentService.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class ComponentService {

  public dataObsevable: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);

  constructor() {
  }

  onDataReceived = (close: boolean) => this.dataObsevable.next(close);

}
Enter fullscreen mode Exit fullscreen mode

component.ts

import { OnInit } from '@angular/core';
import { ComponentService } from '../../componentService.ts';

export class Component implements OnInit {

  public dataObsevable: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(null);

  constructor(
   private componentService: ComponentService 
  ) { }

  /* Is important to always call the method to subscribe in the ngOnInit or constructor */
  ngOnInit() {
    this.onDataChangeReceived();
  }

  onDataChangeReceived = () => {
    this.componentService.onDataReceived.subscribe((change: boolean) => {
      if (change) {
        /*Something*/
      }
    });
  }

}
Enter fullscreen mode Exit fullscreen mode

I hope this will be helpful for all of you and thanks for reading!!

Discussion

pic
Editor guide