BACK
Lessons39. BehaviorSubject: current state
Lessons · 39

39. BehaviorSubject: current state

BehaviorSubject — a Subject that remembers the current value

BehaviorSubject is a Subject that remembers the last value. So:

  • It needs an initial value when created.
  • Every new subscriber instantly gets the current value (a snapshot).
  • You can read the value synchronously via .getValue().
const user$ = new BehaviorSubject('Guest');
user$.subscribe(v => console.log('A:', v));  // → A: Guest (instantly)
user$.next('Admin');                         // → A: Admin
user$.subscribe(v => console.log('B:', v));  // → B: Admin (instantly, the latest)
user$.getValue();                             // → 'Admin' (synchronously)

Where to use it

  • The current user / theme / language — state that always has a value.
  • Simple state storage in an Angular service.
  • Any case where a "late" subscriber must immediately learn the current value.

A modern alternative

In modern Angular, a signal is often more convenient for local state. But BehaviorSubject is still irreplaceable when the state needs to live as an Observable (for the async pipe, for example).

Your task

  1. Create const user$ = new BehaviorSubject('Guest');
  2. Below the first subscription, call user$.next('Admin');
  3. The Current log already uses getValue() — no need to change it.
Solution spoiler · click to reveal
const { BehaviorSubject } = Rx;

const user$ = new BehaviorSubject('Guest');

user$.subscribe(value => console.log('Sub A: ' + value));

user$.next('Admin');

user$.subscribe(value => console.log('Sub B: ' + value));

console.log('Current: ' + user$.getValue());
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...