BehaviorSubject
Requires an initial value and emits the current value to new subscribers
๐ก If you want the last emitted value(s) on subscription, but do not need to supply a seed value, check out ReplaySubject instead!
Examples
Example 1: Simple BehaviorSubject
( Stackblitz )
// RxJS v6+
import { BehaviorSubject } from 'rxjs';
const subject = new BehaviorSubject(123);
// two new subscribers will get initial value => output: 123, 123
subject.subscribe(console.log);
subject.subscribe(console.log);
// two subscribers will get new value => output: 456, 456
subject.next(456);
// new subscriber will get latest value (456) => output: 456
subject.subscribe(console.log);
// all three subscribers will get new value => output: 789, 789, 789
subject.next(789);
// output: 123, 123, 456, 456, 456, 789, 789, 789Example 2: BehaviorSubject with new subscribers created on mouse clicks
( Stackblitz )
Related Recipes
Additional Resources
BehaviorSubject ๐ฐ - Official docs
BehaviorSubject - In Depth Dev Reference
๐ Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/BehaviorSubject.ts
Last updated