Sub topic 12
Subjects: Subject, BehaviorSubject, and ReplaySubject
This chapter assumes you already know how observables, observers, and subscriptions relate to each other. It also assumes you can write a pipe with basic operators and know why unsubscribing matters. You should be comfortable with Angular services and dependency injection.
So far, every observable in this tutorial has had a producer inside it: a timer, an HTTP request, or a form control. A subject is different. You push values into it from outside by calling next(), and it forwards each value to every current subscriber. That makes subjects the usual tool when your own code decides when something happens. Examples include "the user clicked save", "a toast should appear", or "the selected item changed".
A Subject Is Both an Observable and an Observer
A Subject<T> implements both sides of the contract:
- Observer side: it has
next(value),error(err), andcomplete(), so you can feed it values. - Observable side: it has
subscribe()andpipe(), so other code can listen to it.
Inside, a subject keeps a list of its current observers. When you call next(value), it loops over that list and calls each observer's next. Nothing is buffered and nothing runs per subscriber. All observers share one execution, which is why subjects are called multicast.
import { Subject } from 'rxjs';
const events = new Subject<string>();
events.subscribe(v => console.log('A received', v));
events.next('first');
events.subscribe(v => console.log('B received', v));
events.next('second');
events.complete();
events.next('third'); // ignored: the subject is closedOutput:
A received first
A received second
B received secondSubscriber B joined late, so it missed first. A plain Subject has no memory. A value emitted while nobody is listening is lost.
Because a subject is also an observer, you can pass it straight to subscribe on another observable. The subject then forwards that source's values to all of its own subscribers:
import { Subject, from } from 'rxjs';
const relay = new Subject<number>();
relay.subscribe(v => console.log('X', v));
relay.subscribe(v => console.log('Y', v));
from([1, 2, 3]).subscribe(relay);
// X 1, Y 1, X 2, Y 2, X 3, Y 3This is the mechanism under operators such as share and shareReplay, which the next chapter covers.
The Three Common Variants
The variants differ only in what a new subscriber receives at the moment it subscribes.
import { Subject, BehaviorSubject, ReplaySubject } from 'rxjs';
const plain = new Subject<number>();
const behavior = new BehaviorSubject<number>(0);
const replay = new ReplaySubject<number>(2);
for (const s of [plain, behavior, replay]) {
s.next(1);
s.next(2);
s.next(3);
}
plain.subscribe(v => console.log('Subject late:', v));
behavior.subscribe(v => console.log('BehaviorSubject late:', v));
replay.subscribe(v => console.log('ReplaySubject late:', v));Output:
BehaviorSubject late: 3
ReplaySubject late: 2
ReplaySubject late: 3Subjectgives late subscribers nothing from the past.BehaviorSubjectalways holds exactly one current value. It needs an initial value in its constructor and sends the current value to each new subscriber right away. You can also read the value synchronously with.value(orgetValue()).ReplaySubject(bufferSize, windowTime?)stores the lastbufferSizevalues, optionally limited to those emitted within the lastwindowTimemilliseconds. It replays them to each new subscriber.
There is also AsyncSubject, which emits only its last value, and only when it completes. It behaves like a Promise that resolves once. It is rarely needed in Angular code.
| Type | Constructor | New subscriber receives | Synchronous read | Typical Angular use |
|---|---|---|---|---|
| `Subject` | `new Subject<T>()` | Only future values | No | Events and commands: clicks, "refresh now", destroy signals |
| `BehaviorSubject` | `new BehaviorSubject<T>(initial)` | Current value, then future ones | `.value` | Current state: selected item, filter, logged-in user |
| `ReplaySubject` | `new ReplaySubject<T>(n, ms?)` | Last `n` values, then future ones | No | Recent history, or "latest value once one exists" when there is no sensible initial value |
| `AsyncSubject` | `new AsyncSubject<T>()` | Last value, only after completion | No | One-shot results (rare) |
Choosing Between Them
Ask two questions.
- Does a late subscriber need to know what already happened? If not, as with a "save clicked" event, use
Subject. Replaying an old click to a new listener would trigger a duplicate action. - Is there always a meaningful current value? If yes, use
BehaviorSubject. If there is no good initial value, such as a user profile that loads later, useReplaySubject(1). Faking a value likenullforces every consumer to filter it out.
Exposing Subjects Safely from a Service
If a service exposes a subject as a public property, any component can call next(), error(), or complete() on it. One component calling complete() would silently stop the stream for every other consumer. Keep the subject private and expose asObservable(), which returns a view that has no next:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
export interface Toast {
message: string;
kind: 'info' | 'error';
}
@Injectable({ providedIn: 'root' })
export class ToastService {
private readonly toastSubject = new Subject<Toast>();
readonly toasts$ = this.toastSubject.asObservable();
show(message: string, kind: Toast['kind'] = 'info'): void {
this.toastSubject.next({ message, kind });
}
}A plain Subject is the right choice here. A toast container that mounts later should not replay toasts that were already shown. The full state-service pattern built on BehaviorSubject comes in a later chapter.
Lifecycle Rules and Terminal States
When a subject receives complete() or error(), it is closed for good:
- Further
next()calls are ignored. - A new subscriber to a completed
SubjectorBehaviorSubjectreceives onlycomplete. ABehaviorSubjectdoes not send its last value after it completes. - A new subscriber to a completed
ReplaySubjectreceives the buffered values and thencomplete. - A new subscriber to an errored subject receives the error immediately. Reading
.valueon an erroredBehaviorSubjectthrows that error.
Common Mistakes
Emitting before anyone subscribes
import { Subject } from 'rxjs';
const ready = new Subject<void>();
ready.next(); // emitted into the void
ready.subscribe(() => console.log('ready')); // never logsThis often happens when a service calls next() in its constructor before the component subscribes. Use a BehaviorSubject or ReplaySubject(1) if late subscribers must see the value.
Mutating the value held by a BehaviorSubject
import { BehaviorSubject } from 'rxjs';
const items = new BehaviorSubject<string[]>([]);
items.value.push('apple'); // wrong: no emission, subscribers not told
items.next([...items.value, 'apple']); // right: new array, subscribers notifiedMutation fails in two ways. Subscribers are never notified, and OnPush components or distinctUntilChanged see the same reference and skip the update.
Unbounded ReplaySubject buffers
new ReplaySubject<T>() with no arguments keeps every value forever. In a root-provided service on a high-frequency stream, memory grows without limit. Always pass a buffer size, and add a window time if old values become irrelevant.
Using `.value` as a substitute for reactivity
Reading behavior.value inside a component gives you a snapshot that never updates. Subscribe through the async pipe, or derive new streams with pipe(map(...)). Keep .value for code inside the service that needs the current state to compute the next one.
Forgetting that subscribers still need cleanup
A subject in a root service lives as long as the app. A component that subscribes to it manually keeps that subscription alive after the component is destroyed. The rules from the unsubscribing chapter still apply: use the async pipe or takeUntilDestroyed.
Synchronous Delivery
next() delivers values synchronously. When subject.next(x) returns, every subscriber's next handler has already run, in subscription order. If a handler calls next() on the same subject, the nested emission is delivered before the outer loop finishes, and later subscribers can see the values out of order. Avoid feeding a subject from inside its own subscribers. If you cannot avoid it, add observeOn(asapScheduler) to the inner path.
Exercise
A service loads the current user from the server after login. Components that render before the request finishes, and components created long afterwards, should both get the user once it is known, and there is no sensible placeholder user. Which subject should back user$, and why not the other two?
Show answer
Use new ReplaySubject<User>(1). A plain Subject would lose the user for components that subscribe after it was emitted. A BehaviorSubject needs an initial value, so you would have to emit a fake null that every consumer must filter out. ReplaySubject(1) emits nothing until the user arrives, then replays that single latest value to every later subscriber.
Exercise
Predict the console output: const s = new BehaviorSubject(1); s.next(2); s.complete(); s.subscribe({ next: v => console.log('next', v), complete: () => console.log('done') });
Show answer
Only done is printed. Once a BehaviorSubject has completed, it no longer sends its current value to new subscribers. They receive only the completion notification.
Exercise
A CartService exposes public items = new BehaviorSubject<string[]>([]), and a component adds an item with this.cart.items.value.push('book'). The badge showing the item count does not update. Name the two problems and fix them.
Show answer
First, push mutates the existing array without calling next(), so no subscriber is notified, and the reference stays the same for OnPush and distinctUntilChanged. Second, the subject is public, so any component can mutate it or even complete it. Fix both by making the subject private, exposing readonly items$ = this.itemsSubject.asObservable(), and adding a method add(item: string) { this.itemsSubject.next([...this.itemsSubject.value, item]); }.