BehaviorSubject
is a powerful tool that requires an initial value and emits the current value to new subscribers. The initial value is fetched from localStorage
, making it easy to work with stored data.
To access the initial value later, simply add subscribers to this.userSubject
.
When using new BehaviorSubject<User>
, the angle brackets <>
signify that BehaviorSubject
is a generic class and User
serves as a generic type parameter.
For illustration, consider the following example:
// RxJS v6+
import { BehaviorSubject } from 'rxjs';
const subject = new BehaviorSubject(123);
// Two new subscribers will receive the initial value => output: 123, 123
subject.subscribe(console.log);
subject.subscribe(console.log);
// Both subscribers will now get the new value => output: 456, 456
subject.next(456);
// A new subscriber will receive the latest value (456) => output: 456
subject.subscribe(console.log);
// All three subscribers will be updated with the new value => output: 789, 789, 789
subject.next(789);
// Final output sequence: 123, 123, 456, 456, 456, 789, 789, 789