BehaviorSubject, ReplaySubject and AsyncSubject in RxJS (Angular)
Interviewer always interested to know about replaysubject and asyncsubject and we are like: Oh we have never used it.
Lets learn that today,
RxJS provides several types of Subjects that are useful for multicasting.
Multicasting is sharing the same stream of data to multiple subscribers.
BehaviorSubject:
📌 A subject that holds the most recent value and emits it to new subscribers.
📌 Ideal for maintaining global application state
userSubject = new BehaviorSubject<User>(null);
ngOnInit(){
this.userSubject.next({ name: 'John', age: 20 });
this.userSubject.next({ name: 'Doe', age: 22 })
this.userSubject.subscribe((user)=>{
console.log(user) // {name: "Doe", age: 22}
})
}
ReplaySubject:
📌 A subject that replays previously emitted values to new subscribers.
📌 Useful when you want new subscribers to receive historical data.
“We need to provide a buffer size for how many historical data values we want. If we don’t provide it, ReplaySubject will emit all previous values to new subscribers.”
replaySubject = new ReplaySubject<User>(2);
ngOnInit() {
this.replaySubject.next({ name: 'John', age: 20 });
this.replaySubject.next({ name: 'John1', age: 20 });
this.replaySubject.next({ name: 'John3', age: 20 });
this.replaySubject.next({ name: 'John4', age: 20 });
this.replaySubject.subscribe((data) => {
console.log(data); // 3 4
});
}
AsyncSubject:
📌 Emits the last value of the observable only when the observable completes.
📌 Useful when you only care about the final result of an observable sequence (e.g., final calculation result).
asyncSubject= new AsyncSubject<number>()
ngOnInit() {
this.asyncSubject.next(1);
this.asyncSubject.next(2);
this.asyncSubject.complete();
this.asyncSubject.subscribe((data)=>{
console.log(data) // Logs 2 (only the last value is emitted)
})
}
Thanks for reading, Reach me out here for more discussion related to angular.