Sub topic 12
Subjects: Subject, BehaviorSubject, and ReplaySubject
This chapter assumes you know how observables, observers, and subscriptions relate, and that you can write a basic subscribe call. It also assumes you are comfortable with TypeScript generics.
What a Subject Adds
A plain observable is unicast: each subscriber triggers its own run of the producer. A Subject is both an observable and an observer. You can call next, error, and complete on it directly, and every current subscriber receives the same value. That makes it multicast.
Angular code uses subjects to push values from imperative code into a stream. Typical sources are button clicks handled in a method, messages from a WebSocket callback, or state changes inside a service.
The Three Common Variants
The variants differ in what a late subscriber sees, meaning a subscriber that arrives after values have already been emitted.
| Type | Needs initial value | What a new subscriber receives | Typical use |
|---|---|---|---|
| `Subject` | No | Only values emitted after it subscribes | Events, such as "save clicked" |
| `BehaviorSubject` | Yes | The current value, then later values | Current state, such as the logged-in user |
| `ReplaySubject` | No | The last N buffered values, then later values | Recent history, such as the last few messages |
import { Subject, BehaviorSubject, ReplaySubject } from 'rxjs';
const subject = new Subject<number>();
subject.next(1); // no subscribers yet, so this value is lost
subject.subscribe(v => console.log('Subject:', v));
subject.next(2); // Subject: 2
const behavior = new BehaviorSubject<number>(0);
behavior.next(1);
behavior.subscribe(v => console.log('Behavior:', v)); // Behavior: 1
behavior.next(2); // Behavior: 2
console.log('Current value:', behavior.value); // Current value: 2
const replay = new ReplaySubject<number>(2);
replay.next(1);
replay.next(2);
replay.next(3);
replay.subscribe(v => console.log('Replay:', v)); // Replay: 2, Replay: 3The value getter on BehaviorSubject gives you a synchronous read of the current state. The other two subjects have no equivalent.
Common Errors
- Using
Subjectfor state. A component that subscribes after the lastnextsees nothing until the next change. If subscribers need "the value right now," useBehaviorSubject. - Leaving the
ReplaySubjectbuffer unbounded.new ReplaySubject()with no size keeps every value it has ever received. That grows memory for a long-lived service. Always pass a buffer size, and optionally a time window as the second argument. - Emitting after
completeorerror. Once a subject completes or errors, laternextcalls are silently ignored. New subscribers immediately receive the terminal notification. A subject cannot be reused after that. - Exposing the subject itself. If a service makes its subject public, any consumer can call
next. Exposesubject.asObservable()so that only the owner can push values. A later chapter builds a full state service with this pattern. - Forgetting to unsubscribe. Subjects in root services usually never complete, so subscriptions to them leak just as easily as subscriptions to
interval. Use the async pipe ortakeUntilDestroyed.
Exercise
A notifications service keeps the last 5 toast messages so that a panel opened later can show them. Which subject type should it use, and how should it be constructed?
Show answer
A ReplaySubject with a buffer size of 5: new ReplaySubject<string>(5). A Subject would show nothing to a panel opened later. A BehaviorSubject holds only one value and needs an initial value. An unbounded ReplaySubject would keep every message forever.
Exercise
A BehaviorSubject<number>(10) receives next(20) and then complete(). A new subscriber then subscribes. What does it receive?
Show answer
Only the complete notification. A BehaviorSubject that has completed does not replay its last value to new subscribers. It signals completion immediately.