Skip to main content

What does BehaviorSubject do in state services?

BehaviorSubject is a type of Subject from the RxJS library that stores the last emitted value and immediately gives it to new subscribers.

In state services, it's used to:

  1. Store the current state (for example, the current user, settings, a loading flag).
  2. Let components subscribe to the stream and get both the current value and all subsequent changes.
  3. Change the state by calling next(), which automatically notifies every subscribed component.

Roughly like this:

typescript
private user$ = new BehaviorSubject<User | null>(null); setUser(user: User) { this.user$.next(user); } getUser(): Observable<User | null> { return this.user$.asObservable(); }

Unlike a Subject, a BehaviorSubject requires an initial value and always emits the latest one to a new subscription.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.