rxjs

Subject and BehaviorSubject

Subject and BehaviorSubject

In this tutorial, we will learn about the subject and  BehaviorSubject of RXJS.

Subject

The subject is mostly used for cross-component data share/Communication

The subject is a special type of observable because 

In subject works as obserbable and observer also

We can do bloabaly data communication using subject

The subject is Multicasting observable means we will get data from when we subscribed not previous data

Example:

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

@Injectable()
export class DataService {

  username = new Subject <string>("Jigar");

  constructor() { }

  updatedDataSelection(data){
    this.username.next(data);
  }
  
}

We can call next and pass in a new value to the Subject.  

 import { Component, OnInit } from "@angular/core";
import { DataService } from "./data.service";

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
})
export class HeaderComponent implements OnInit {
  constructor(private dataService : DataService ) {}

  exclusive = false;

  ngOnInit() {
    this.dataService.username.next('rahul');
  }
  
}

For getting the updated value we can subscriber observable as below:

 import { Component, OnInit } from "@angular/core";
import { DataService } from "./data.service";

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
})
export class HeaderComponent implements OnInit {
  constructor(private dataService : DataService ) {}

  exclusive = false;

  ngOnInit() {
    this.dataService.exclusive.subscribe((res) => {
      console.log(res):
    });
  }
}

BehaviorSubject 

A BehaviorSubject a Subject that can emit the current value while Subjects have no concept of current value.

Example:

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

@Injectable()
export class DataService {

  username = new BehaviorSubject<string>("Jigar");

  constructor() { }

  updatedDataSelection(data){
    this.username.next(data);
  }
  
}

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment