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!


Ultimate RxJS

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, 789

Example 2: BehaviorSubject with new subscribers created on mouse clicks

( Stackblitz )

Additional Resources


๐Ÿ“ Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/BehaviorSubject.ts

Last updated