What is the difference between a BehaviorSubject and a regular Subject
Both BehaviorSubject
and Subject
are a type of Observable that we can use to stream data throughout our application.
The main difference, is that the BehaviorSubject
has an initial value, and when you subscribe to it, it will give you
the last value it emitted.
import { Component } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
myBehaviosSubject$ = new BehaviorSubject<string>('I have an initial value');
myRegularSubject$ = new Subject<string>();
constructor() {}
}
The regular Subject
doesn’t have an initial value, and even if it has been emitting data, when you subscribe to it you
won’t get any data until it emits something again.
You can see the full app example directly in its GitHub repo here.
By the way, do you want to jump-start your development using the Firebase modular SDK with AngularFire?
Download my free book that will take you from creating an app to properly using Firebase Auth and Firestore.
Read other posts