DEV Community

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

Posted on

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

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!!

Top comments (1)

Collapse
 
amirensit profile image
choubani amir

What is the use of dataObsevable property on component.ts file ?
I think it should be removed from there.