← Back to Angular, page 3

angular-0056 · Easy fresher

What are Subject, BehaviorSubject, ReplaySubject and AsyncSubject, and how do they differ?

A Subject is both an Observable and an observer, so you can push values into it and many subscribers receive them (multicast). BehaviorSubject needs an initial value and gives new subscribers the latest value. ReplaySubject replays a set number of past values. AsyncSubject emits only the last value, and only when it completes.

Full answer

A normal Observable such as http.get() is cold. Each subscriber starts its own run. A Subject is hot: it exists on its own, you call next() on it, and every current subscriber receives the value.

The four kinds differ in what a late subscriber receives:

  • Subject: nothing from the past. A subscriber sees only values emitted after it subscribed. Good for events such as "user clicked save".
  • BehaviorSubject(initial): always holds a current value. A new subscriber immediately gets the latest one. You can read it with .value or getValue(). Good for state such as "current user".
  • ReplaySubject(n): remembers the last n values and replays them to each new subscriber. Good for a short history.
  • AsyncSubject: emits only the last value, and only when complete() is called. Good for a single result that is shared.

Errors and completion: after error() or complete() a Subject is finished. A late subscriber to a completed Subject receives only the completion (and replayed values for a ReplaySubject).

Practical rules: expose a Subject as an Observable with asObservable() so that outside code cannot call next(). In modern Angular many uses of BehaviorSubject for state are better served by a signal, which has a synchronous read and no subscription to clean up. Subjects are still the right tool for event streams such as search input or a message bus.

The script below shows what each late subscriber receives.

typescript
import { AsyncSubject, BehaviorSubject, ReplaySubject, Subject } from 'rxjs';

const subject = new Subject<number>();
const behavior = new BehaviorSubject<number>(0);
const replay = new ReplaySubject<number>(2);
const last = new AsyncSubject<number>();

for (const n of [1, 2, 3]) {
  subject.next(n);
  behavior.next(n);
  replay.next(n);
  last.next(n);
}

// Everyone subscribes late, after 1, 2, 3 were emitted.
subject.subscribe((v) => console.log('Subject       ', v)); // nothing yet
behavior.subscribe((v) => console.log('BehaviorSubject', v)); // 3
replay.subscribe((v) => console.log('ReplaySubject  ', v)); // 2, 3
last.subscribe((v) => console.log('AsyncSubject   ', v)); // waits for complete

console.log('--- emit 4 and complete');
subject.next(4);
behavior.next(4);
replay.next(4);
last.next(4);
last.complete();

// Expose state without letting outsiders push values.
class Counter {
  private readonly state = new BehaviorSubject(0);
  readonly value$ = this.state.asObservable();

  increment(): void {
    this.state.next(this.state.value + 1);
  }
}

const counter = new Counter();
counter.value$.subscribe((v) => console.log('Counter', v));
counter.increment();

Tested with RxJS 7 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`), twice with identical output.

Key points

  • A Subject is hot and multicast. `next()` pushes a value to all subscribers.
  • `BehaviorSubject` has a current value. `ReplaySubject(n)` replays `n` values. `AsyncSubject` gives the last value on completion.
  • Expose it with `asObservable()` and keep `next()` private.
  • For state, a signal is often simpler. For events, use a Subject.

Common mistakes

  • Exposing a public `BehaviorSubject` so any component can call `next()` on it.
  • Using a plain `Subject` for state, so late subscribers see nothing.
  • Forgetting to unsubscribe from a Subject that never completes.

Follow-ups

  • What is the difference between a cold and a hot Observable?
  • Why would you pick a signal instead of a BehaviorSubject?
  • What happens if you subscribe to a completed ReplaySubject?

Tips

  • Make a table in your head: what does a late subscriber get? It is the clearest answer.
  • Mention `asObservable()` to show you think about encapsulation.
  • Say that you use signals for state in new code.

Evaluation rubric

  • Explains hot versus cold and multicast.
  • Distinguishes all four subject types by late-subscriber behaviour.
  • Knows the encapsulation practice.