RxJS 09 ๐ฃ Subjects & Reactive State โ Understanding Subject, BehaviorSubject, ReplaySubject, and AsyncSubject
A Subject is both an Observable and an Observer. It is an Observable because you can subscribe to it and receive values. It is an Observer because it has next, error, and complete methods you call yourself. That dual nature is what makes it the seam between the imperative world โ a button handler, a WebSocket message, a service method โ and the reactive world of pipes and operators. Outside of a Subject, an observable produces its own values; inside a Subject, you produce them.
The four classes in this chapter are the base Subject and three specialisations, and each answers one additional question about what a subscriber sees. A plain Subject starts every subscriber at the present moment and never looks back. A BehaviorSubject starts every subscriber with the current value and remembers only that one. A ReplaySubject starts every subscriber with the last n values and remembers all of them within a buffer. An AsyncSubject holds every value back, emits only the final one, and only when the subject completes. The choice is the answer to “what does a subscriber who arrives late get?”.
This matters because almost every application state container, event bus, or service boundary is built on one of these four. Get the class wrong and the symptom is subtle: a component that renders blank because it subscribed after the value was set, a panel that never updates because the subject only fires on click, a memory leak because the subscribe was never torn down. The chapter opens with why Subjects exist at all, then walks each of the four with its exact late-subscriber semantics, then assembles a complete store built from the operators and subjects covered.
Key point: a plain Subject is stateless multicast โ a subscriber that arrives after a next never sees it. Behaviour is added by the exact class you pick: BehaviorSubject remembers one value and gives it to every new subscriber immediately; ReplaySubject remembers a configurable buffer; AsyncSubject remembers everything internally and releases only the last value at completion. Late-subscriber behaviour is the entire difference.
Why subjects exist
The multicast problem. Observables are cold by default. Each subscription to http.get('/api/user') starts a fresh request; each subscription to fromEvent(el, 'click') adds a fresh DOM listener. Two components that both need the user object make two requests. Two components that both react to a click add two listeners, and the click handler runs twice. A Subject is hot multicast: one source, many listeners, one execution. This is the reason a service holds a Subject and exposes its asObservable() rather than returning a fresh cold observable from every method.
The imperative-source problem. Half of the events in a frontend are not observable at their origin. A WebSocket message arrives in a callback. A form validation is triggered by a direct method call. A service method is called by a component that has never heard of RxJS. A Subject is the adaptor: the imperative caller calls next(value), and the stream turns that value into a push. Without a Subject, the imperative side of the code cannot participate in a reactive pipeline at all.
The late-subscriber problem. A plain cold observable emits only while subscribed, so a component that mounts one frame late never sees the initial value. A store must give the current state to every subscriber, no matter when it subscribed. That is BehaviorSubject, and it is the reason the class is the default state container in almost every RxJS codebase. ReplaySubject generalises the same idea to “give the last n values”, and AsyncSubject extends it to “give the last value, but only after the operation finished”.
The state problem. A BehaviorSubject with an initial value is a state container with an observable edge. It has a synchronous read (.value), an asynchronous read (subscribe), and a mutation (next). This triple covers every consumer: a template, an effect, and an imperative handler can all read the same value using whichever access matches their context. A cold observable cannot do this because there is no current value to read.
The read/write separation problem. The moment state is exposed as a Subject, every consumer can call next. That is a hazard: components that should not be writing state can write it, and the only guarantee of invariant-protecting updates is convention. asObservable() is the language-level answer โ it returns a read-only view of the same underlying subject. Combined with private readonly on the original, the compiler enforces the boundary, and any attempt to mutate from outside becomes a compile error rather than a bug report.
The completion-signal problem. Some flows are not a stream; they are a single final value that must be received once the work is definitely done. A cold observable that completes carries its value, but a late subscriber that arrives after completion re-runs the operation. AsyncSubject is the opposite: it has already buffered the value, still has not released it, and releases it only on complete(). That makes it the natural container for a long-running initialisation result that any late caller must see without re-triggering.
a. Subject โ multicast with no memory
new Subject<T>() is the base class. It forwards every next to every current subscriber, and it does not retain any value. A subscriber that arrives after a next has happened receives nothing for that emission. When the subject completes, every current subscriber receives complete, and every future subscriber receives complete immediately and nothing else.
import { Subject } from 'rxjs';
const bus$ = new Subject<string>();
// Subscriber A subscribes before anything is emitted
bus$.subscribe((v) => console.log('A:', v));
bus$.next('hello'); // A: hello
bus$.next('world'); // A: world
// Subscriber B arrives after two emissions
bus$.subscribe((v) => console.log('B:', v));
bus$.next('again'); // A: again, B: again
bus$.complete(); // A complete, B complete
The output shows the whole contract. Subscriber A saw hello, world, again. Subscriber B saw only again. There is no replay, no buffer, and no way to ask what was emitted before.
This behaviour is deliberate and it is exactly what an event bus needs. A button click has no history: an event that already fired should not be replayed to a new listener. A “logout requested” signal should not re-fire when a new module subscribes. The plain Subject is the right class whenever the semantics are events rather than state.
A Subject is also an Observer, which means it can be passed directly to subscribe as the destination of another observable. That is how a cold source is turned into a hot shared one without share().
import { fromEvent } from 'rxjs';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';
const clicks$ = new Subject<MouseEvent>();
// Bridge a DOM event into the subject: one listener, many subscribers
fromEvent(document, 'click').subscribe(clicks$);
// Two downstream consumers share the same subject; the DOM listener
// is created once, not twice
clicks$.pipe(map((e) => e.clientX)).subscribe(logX);
clicks$.pipe(map((e) => e.clientY)).subscribe(logY);
Two methods exist for inspection. bus$.observed is a boolean that is true when at least one observer is subscribed. bus$.observers is the live array of subscribers, useful in tests and debugging but not a public contract. Both exist because the number of subscribers on a Subject is often the number you need to audit when hunting a leak.
Calling bus$.error(err) terminates the subject permanently, exactly as complete() does, except the terminal notification is an error. The subject cannot be reused afterwards โ every future subscriber gets that error immediately, and every next afterwards is silently ignored.
b. BehaviorSubject โ the single current value
new BehaviorSubject<T>(initialValue) is the base Subject plus one rule: it always has a current value, and every new subscriber receives that value synchronously on subscribe, before any subsequent emission. The value is set at construction (the initial argument) and replaced on every next. It is read synchronously via .value.
import { BehaviorSubject } from 'rxjs';
const theme$ = new BehaviorSubject<'light' | 'dark'>('light');
theme$.subscribe((v) => console.log('A:', v)); // A: light (immediate)
theme$.next('dark'); // A: dark
// Subscriber B arrives after the change and gets the current value
theme$.subscribe((v) => console.log('B:', v)); // B: dark (immediate)
theme$.next('light'); // A: light, B: light
// Synchronous read, no subscription required
console.log(theme$.value); // 'light'
The initial value is mandatory. That is the class’s defining constraint, and it is the reason BehaviorSubject is not the right tool when there is no sensible default โ in that case ReplaySubject(1) or a Subject<State | null>(null) with an explicit null seed is the correct substitution.
A subtlety worth knowing: BehaviorSubject.value throws if the subject has been errored or unsubscribed. Reading it inside a reactive pipeline is fine, but reading it inside a try/catch that swallows errors can hide a completed subject for a long time. In normal operation the getter is safe and is the fastest read available.
The canonical store pattern is the private readonly subject with asObservable() on a public property, plus a set/patch method that owns the mutation.
import { BehaviorSubject, Observable } from 'rxjs';
interface Settings {
readonly theme: 'light' | 'dark';
readonly locale: string;
}
const DEFAULTS: Settings = { theme: 'light', locale: 'en' };
class SettingsStore {
// Private: no outside caller can call .next
private readonly subject = new BehaviorSubject<Settings>(DEFAULTS);
// Public: a read-only view of the same underlying subject
readonly settings$: Observable<Settings> = this.subject.asObservable();
// Imperative reads are supported because the value exists
get snapshot(): Settings {
return this.subject.value;
}
patch(partial: Partial<Settings>): void {
// Always spread from the current value, never replace wholesale
this.subject.next({ ...this.subject.value, ...partial });
}
}
asObservable() returns an Observable that shares the subject’s internal observer list. It is the same source, not a copy. The convenience is that the returned object has no next, error, or complete methods, so consumers cannot mutate state even accidentally. That is the entire read/write separation pattern in one line.
One more thing is worth pinning down. shareReplay({ bufferSize: 1 }) looks like a BehaviorSubject but is not the same tool. shareReplay is a pipe operator applied to a cold observable, and its cache is populated by whatever the source emits. BehaviorSubject is a source and a sink, with its own writable state. If you need to write into the store, a subject is required. If you need to cache an upstream result and do not need to write, shareReplay is often better because it refcounts.
c. ReplaySubject โ the configurable buffer
new ReplaySubject<T>(bufferSize?, windowTime?) is the general memory. Every emission is stored in a buffer, and every new subscriber receives the full buffer synchronously on subscribe, then all subsequent emissions. Both bufferSize and windowTime default to Infinity, which means the buffer holds every value ever emitted and never expires.
import { ReplaySubject } from 'rxjs';
// Buffer the last two values; no time limit
const last2$ = new ReplaySubject<number>(2);
last2$.next(1);
last2$.next(2);
last2$.next(3);
last2$.subscribe((v) => console.log('late:', v)); // late: 2, late: 3
last2$.next(4); // late: 4
The output is exactly the last two values, in order, delivered synchronously on subscribe. The three earlier values are gone. That is the mental model: a rolling window of the most recent emissions.
The windowTime parameter adds an age cutoff. A value older than windowTime milliseconds when a new subscriber arrives is not replayed, even if it is still inside the bufferSize.
import { ReplaySubject } from 'rxjs';
// Margin: keep up to 5 values, but only those from the last 2000ms
const recent$ = new ReplaySubject<number>(5, 2000);
recent$.next(1); // timestamp t0
recent$.next(2); // timestamp t0 + 100
// ... 2500ms pass with no emissions ...
// At t0 + 2600, both values are older than the 2000ms window,
// so a subscriber that now arrives sees an empty replay
recent$.subscribe((v) => console.log('late:', v));
recent$.next(3); // late: 3 (this one is inside the window)
The combination of bufferSize and windowTime is what makes ReplaySubject correct for “show the user what just happened” notifications โ the last five toast messages from the last two seconds. It is genuinely useful there and genuinely dangerous elsewhere. An unbounded ReplaySubject on a stream that never stops emitting will hold every value forever; this is the single most common memory leak in the family.
The safe patterns are worth stating explicitly. Prefer ReplaySubject(1) over a bare ReplaySubject() unless you specifically need a longer history. Always provide a windowTime if the source is high frequency. And if you want a replayable cache that does not need to be written into, shareReplay({ bufferSize: 1, refCount: true }) is usually the better choice because it releases its cache when the last subscriber unsubscribes.
import { of } from 'rxjs';
import { shareReplay, mergeMap } from 'rxjs/operators';
// Caching the result of a cold HTTP-like observable without a Subject
const cached$ = http.get<User[]>('/api/users').pipe(
// One subscription upstream, last value replayed, refcounted so
// the cache is discarded when no one is listening
shareReplay({ bufferSize: 1, refCount: true })
);
// Both subscribers hit the same upstream subscription
cached$.subscribe(render);
cached$.subscribe(log);
ReplaySubject(1) and BehaviorSubject(initial) differ only in the initial value. If a “no value yet” state is meaningful, either seed the BehaviorSubject with null and model the union explicitly, or use ReplaySubject(1) and accept that a subscriber before the first emission receives nothing. There is no third option that preserves both properties.
d. AsyncSubject โ the terminal value
new AsyncSubject<T>() is the least-used of the four and the most specific. It holds every next internally, and when complete() is called it emits only the last value to every current subscriber and then completes. A subscriber that arrives before complete() sees nothing until complete(). A subscriber that arrives after complete() sees the final value synchronously and then complete.
import { AsyncSubject } from 'rxjs';
const init$ = new AsyncSubject<'ready' | 'failed'>();
// A subscribes before the operation completes
init$.subscribe({
next: (v) => console.log('A next:', v),
complete: () => console.log('A complete')
});
init$.next('ready');
init$.next('failed'); // held internally, not emitted
// B subscribes before completion
init$.subscribe({
next: (v) => console.log('B next:', v)
});
// Still nothing has been printed by A or B
init$.complete();
// A next: failed
// A complete
// B next: failed
// A subscriber that arrives after completion receives the last value
init$.subscribe((v) => console.log('C next:', v)); // C next: failed
The behaviour is the exact opposite of the plain Subject. A late subscriber is the only subscriber guaranteed to see a value synchronously. An early subscriber must wait for completion. And an error discards every buffered value entirely โ a subscriber that receives the error sees no value at all.
AsyncSubject is what you reach for when none of the four flattening operators and none of the four combination operators fit the shape. The shape is: “one value, at the end, delivered to every subscriber that arrives at any point, and only one execution of the work.” That is usually an initialisation result โ a boot config, a WebSocket handshake, a permission check โ where you want every late caller to receive the result without re-running the initialisation.
import { AsyncSubject, Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
let started = false;
const boot$ = new AsyncSubject<BootConfig>();
function ensureBooted(): Observable<BootConfig> {
if (!started) {
started = true;
// Run the boot chain exactly once
loadConfig()
.pipe(switchMap((cfg) => openSocket(cfg)))
.subscribe(boot$);
}
// Every caller gets the same subject, which will emit on complete
return boot$.asObservable();
}
// Both call sites get the same BootConfig without re-booting
ensureBooted().subscribe(startApp);
ensureBooted().subscribe(startAnalytics);
AsyncSubject is also the type that a WebSocketSubject ultimately behaves like when the socket closes cleanly โ a single terminal value. That is a detail of the WebSocket subject, not of the base class, but it explains why the class exists in the first place: to model a connection whose whole lifecycle collapses to one final result.
e. Composing subjects into reactive state
A single subject holding a state object is workable, but it has a granularity problem. A subscriber that only cares about theme re-renders on every change to locale, user, and every other field. The fix is not smaller subjects; it is to keep one source and derive narrower views with operators.
import { BehaviorSubject, Observable } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
interface AppState {
readonly user: User | null;
readonly theme: 'light' | 'dark';
readonly locale: string;
}
const state$ = new BehaviorSubject<AppState>({
user: null,
theme: 'light',
locale: 'en'
});
// Derive a narrow slice. `distinctUntilChanged` collapses every
// state emission that did not change `theme` into nothing.
const theme$: Observable<'light' | 'dark'> = state$.pipe(
map((s) => s.theme),
distinctUntilChanged()
);
// Derive a boolean that flips only when the answer changes
const signedIn$: Observable<boolean> = state$.pipe(
map((s) => s.user !== null),
distinctUntilChanged()
);
The distinctUntilChanged after every map is not optional. Without it, every state emission propagates through every derived stream, and the “narrow slice” is narrow in type but not in traffic. With it, the theme subscriber runs only when the theme value actually changes. That pattern is the entire point of splitting a BehaviorSubject<State> into derived observables in the first place.
A second common structure is to combine several independent subjects. This is where user input, filters, and a selection form one criteria object.
import { BehaviorSubject, combineLatest } from 'rxjs';
import { map, debounceTime, distinctUntilChanged } from 'rxjs/operators';
const term$ = new BehaviorSubject<string>('');
const sort$ = new BehaviorSubject<'relevance' | 'date'>('relevance');
const page$ = new BehaviorSubject<number>(1);
const query$ = combineLatest([term$, sort$, page$]).pipe(
map(([term, sort, page]) => ({ term, sort, page })),
debounceTime(200),
distinctUntilChanged((a, b) =>
a.term === b.term && a.sort === b.sort && a.page === b.page
)
);
query$.subscribe((q) => http.get<Result[]>('/api/search', { params: q }));
Because every operand is a BehaviorSubject with a seed value, the combineLatest emits immediately without waiting for user interaction. That is the mechanical advantage of BehaviorSubject over Subject in combination pipelines: the startWith calls that would otherwise be mandatory are unnecessary because the subject already carries its initial value.
The third pattern is the reducer store, where a Subject carries actions and scan folds them into state. It is the model that survives a long-lived application whose state transitions are the interesting part.
import { BehaviorSubject, Subject, Observable } from 'rxjs';
import { scan } from 'rxjs/operators';
type Action =
| { type: 'userChanged'; user: User | null }
| { type: 'themeToggled' };
function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case 'userChanged':
return { ...state, user: action.user };
case 'themeToggled':
return { ...state, theme: state.theme === 'light' ? 'dark' : 'light' };
default:
return state;
}
}
class Store {
// Actions are a plain Subject: they are events, not state
private readonly actions = new Subject<Action>();
// State is a BehaviorSubject: it always has a current value
private readonly state = new BehaviorSubject<AppState>({
user: null,
theme: 'light',
locale: 'en'
});
readonly state$: Observable<AppState> = this.state.asObservable();
constructor() {
// Fold every action into the current state and push the result
this.actions.pipe(scan(reducer, this.state.value)).subscribe(this.state);
}
dispatch(action: Action): void {
this.actions.next(action);
}
}
The construction order matters. The scan is seeded with this.state.value, which is the same initial object the BehaviorSubject already holds. The subscription started in the constructor means every dispatched action reaches the state subject, even when no external subscriber is attached yet. That is the reason scan alone on top of a Subject is not enough: the scan only runs when subscribed, so a dispatch before the first subscription would be lost. Pushing into a BehaviorSubject closes that gap.
Complete Example Session
// ============================================
// PART 1: IMPORTS AND SHARED VALUES
// ============================================
import {
Subject, BehaviorSubject, ReplaySubject, AsyncSubject,
Observable, combineLatest, merge
} from 'rxjs';
import {
map, filter, distinctUntilChanged, debounceTime,
scan, shareReplay, switchMap
} from 'rxjs/operators';
interface AppState {
readonly user: User | null;
readonly theme: 'light' | 'dark';
}
const INITIAL: AppState = { user: null, theme: 'light' };
// ============================================
// PART 2: Subject AS AN EVENT BUS
// ============================================
const bus$ = new Subject<{ type: string; payload?: unknown }>();
// Two listeners; each one adds its own handler; the bus is hot
bus$.subscribe((e) => console.log('audit', e.type));
bus$.subscribe((e) => console.log('trace', e.type));
bus$.next({ type: 'opened' }); // audit opened, trace opened
bus$.next({ type: 'navigated' }); // audit navigated, trace navigated
// ============================================
// PART 3: BehaviorSubject AS STATE
// ============================================
const theme$ = new BehaviorSubject<'light' | 'dark'>('light');
// A subscriber before any change gets the current value immediately
theme$.subscribe((v) => paint(v)); // paint('light')
theme$.next('dark'); // paint('dark')
// A subscriber that arrives later also gets the current value
theme$.subscribe((v) => remember(v)); // remember('dark')
// Synchronous read for the imperative path
document.body.dataset.theme = theme$.value; // 'dark'
// ============================================
// PART 4: ReplaySubject AS A NOTIFICATION BUFFER
// ============================================
// Last 3 toasts, no more than 5 seconds old
const toast$ = new ReplaySubject<{ id: number; text: string }>(3, 5000);
toast$.next({ id: 1, text: 'Saved' });
toast$.next({ id: 2, text: 'Synced' });
toast$.next({ id: 3, text: 'Queued' });
toast$.next({ id: 4, text: 'Done' });
// New consumers see only the last three, in order
toast$.subscribe((t) => renderToast(t)); // 2, 3, 4
// ============================================
// PART 5: AsyncSubject AS A ONE-SHOT RESULT
// ============================================
const config$ = new AsyncSubject<{ apiUrl: string }>();
loadConfigFromDisk().subscribe(config$); // completes on success
// Both of these callers see the same final config exactly once
config$.subscribe((cfg) => initHttp(cfg));
config$.subscribe((cfg) => initLogger(cfg));
// Neither receives anything until loadConfigFromDisk completes
// ============================================
// PART 6: asObservable TO SEPARATE READ AND WRITE
// ============================================
class ThemeService {
private readonly subject = new BehaviorSubject<'light' | 'dark'>('light');
readonly theme$: Observable<'light' | 'dark'> = this.subject.asObservable();
set(theme: 'light' | 'dark'): void {
this.subject.next(theme);
}
}
const themeService = new ThemeService();
themeService.theme$.subscribe(paint);
themeService.set('dark');
// ============================================
// PART 7: COMBINING TWO SUBJECTS
// ============================================
const user$ = new BehaviorSubject<User | null>(null);
const theme2$ = new BehaviorSubject<'light' | 'dark'>('light');
// Fires immediately with [null, 'light']; then on any change
combineLatest([user$, theme2$]).pipe(
map(([user, theme]) => ({ user, theme, signedIn: user !== null })),
distinctUntilChanged((a, b) =>
a.signedIn === b.signedIn && a.theme === b.theme
)
).subscribe(renderShell);
// ============================================
// PART 8: THE REDUCER STORE
// ============================================
type Action =
| { type: 'login'; user: User }
| { type: 'logout' }
| { type: 'toggleTheme' };
function reducer(state: AppState, action: Action): AppState {
switch (action.type) {
case 'login': return { ...state, user: action.user };
case 'logout': return { ...state, user: null };
case 'toggleTheme': return {
...state,
theme: state.theme === 'light' ? 'dark' : 'light'
};
}
}
class Store {
private readonly actions = new Subject<Action>();
private readonly state = new BehaviorSubject<AppState>(INITIAL);
readonly state$: Observable<AppState> = this.state.asObservable();
readonly user$: Observable<User | null> = this.state.pipe(
map((s) => s.user),
distinctUntilChanged()
);
constructor() {
this.actions.pipe(
scan(reducer, this.state.value)
).subscribe(this.state);
}
dispatch(action: Action): void {
this.actions.next(action);
}
}
const store = new Store();
store.dispatch({ type: 'login', user: currentUser });
// ============================================
// PART 9: LATE-SUBSCRIBER BEHAVIOUR SIDE BY SIDE
// ============================================
const s = new Subject<number>();
const bs = new BehaviorSubject<number>(0);
const rs = new ReplaySubject<number>(2);
const as = new AsyncSubject<number>();
[s, bs, rs, as].forEach((subject) => {
subject.next(1);
subject.next(2);
subject.next(3);
subject.complete();
// Subscriber attached AFTER the terminal notification
subject.subscribe({
next: (v) => console.log(subject.constructor.name, 'next', v),
complete: () => console.log(subject.constructor.name, 'complete')
});
});
// Output:
// Subject complete
// BehaviorSubject complete
// ReplaySubject next 2
// ReplaySubject next 3
// ReplaySubject complete
// AsyncSubject next 3
// AsyncSubject complete
// ============================================
// PART 10: THE ASSEMBLED STORE
// ============================================
const search$ = new BehaviorSubject<string>('');
const sortBy$ = new BehaviorSubject<'relevance' | 'date'>('relevance');
const results$ = combineLatest([search$, sortBy$]).pipe(
debounceTime(250),
distinctUntilChanged((a, b) => a[0] === b[0] && a[1] === b[1]),
switchMap(([term, sort]) =>
term.length < 2
? of([])
: http.get<Result[]>(`/api/search?q=${term}&sort=${sort}`)
),
shareReplay({ bufferSize: 1, refCount: true })
);
store.state$.pipe(
// Re-run the search whenever the user changes
switchMap(() => results$)
).subscribe(renderResults);
The ten parts built an event bus from a plain Subject, a theme state container from a BehaviorSubject, a bounded notification buffer from a ReplaySubject, a one-shot boot config from an AsyncSubject, the read/write separation via asObservable(), the combination of two subjects with combineLatest, a reducer store with scan pushing into a state subject, an explicit late-subscriber comparison of all four classes, and an assembled pipeline that uses the store and the search together.
Quick Reference
The Four Subject Types
| Class | New subscriber receives | Remembers |
|---|---|---|
Subject | nothing until the next next | nothing |
BehaviorSubject(v) | v (current value) immediately | one value |
ReplaySubject(n, t?) | last n values (within t ms) | up to n |
AsyncSubject | last value, immediately if after complete | every value until complete |
Terminal Behaviour
| Method | Subject | BehaviorSubject | ReplaySubject | AsyncSubject |
|---|---|---|---|---|
next after complete | ignored | ignored | ignored | ignored |
New subscriber after complete | complete only | complete only | buffer + complete | last value + complete |
New subscriber after error | error only | error only | error only | error only |
complete emits a value | no | no | no | yes (last value) |
Methods and Properties
| Member | Purpose |
|---|---|
.next(v) | push a value to all subscribers |
.error(e) | terminate with error; subject is dead afterwards |
.complete() | terminate normally; subject is dead afterwards |
.asObservable() | read-only view; hides next/error/complete |
.value | synchronous read (BehaviorSubject only) |
.observed | true if at least one subscriber is attached |
.observers | live array of current subscribers |
Choosing a Subject
| Need | Class |
|---|---|
| Event bus / broadcast | Subject |
| Current state / theme / user | BehaviorSubject |
| Last-n notifications | ReplaySubject(n) |
| One-shot boot config | AsyncSubject |
| Cache an upstream result | shareReplay, not a subject |
| “No value yet” state | BehaviorSubject<State | null>(null) |
Best Practices
โ Do This:
// Keep the subject private and expose a read-only view
private readonly subject = new BehaviorSubject<State>(initial); // โ
// Derive narrow slices with distinctUntilChanged
state$.pipe(map((s) => s.theme), distinctUntilChanged()); // โ
// Seed combineLatest with BehaviorSubjects instead of startWith
combineLatest([term$, sort$]); // โ
// Bound the buffer on any ReplaySubject that sees frequent events
new ReplaySubject<Toast>(3, 5000); // โ
// Push a scan result into a BehaviorSubject so late callers see it
actions.pipe(scan(reducer, initial)).subscribe(state); // โ
// Tear down the subscription when the consumer goes away
state$.pipe(takeUntil(destroy$)).subscribe(render); // โ
// Use one shared subject for one connection, not one per subscriber
const bus$ = new Subject<Message>(); // โ
โ Don’t Do This:
// Expose the raw subject; consumers can now call next
readonly state$ = new BehaviorSubject<State>(initial); // โ
// Subscribe to a subject without tearing down
store.state$.subscribe(render); // โ in a component
// Unbounded ReplaySubject on a high-frequency source
new ReplaySubject<number>(); // โ on mousemove
// Read .value inside a reactive pipeline instead of the stream
state$.pipe(map(() => this.subject.value)); // โ
// Call next after the subject errored; nothing happens
subject.error(err); subject.next(1); // โ
// Replace the state object instead of spreading it
subject.next({ theme: 'dark' }); // โ loses other keys
// Use a Subject where the subscriber needs the initial value
const user$ = new Subject<User>(); // โ if state
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Blank UI on first render | Subscriber attached after the value | BehaviorSubject |
| Memory leak in a component | Subscription never unsubscribed | takeUntil(destroy$), AsyncPipe |
| Every field re-renders | No distinctUntilChanged after map | Add the operator to each slice |
combineLatest never fires | Operand is a Subject, not a BehaviorSubject | startWith or switch classes |
| Browser tab grows unbounded | ReplaySubject() with no buffer size | ReplaySubject(n), shareReplay |
| Subject is dead after one error | error() terminates permanently | Route errors through a separate stream |
| State lost on a dispatch | scan runs only when subscribed | Push into a BehaviorSubject |
| Late subscriber gets no value | Subject was correct for events, wrong for state | Change the class, not the subscriber |
Real-World Examples
1. Event bus
const bus$ = new Subject<Event>();
bus$.subscribe(handle);
2. Theme state
const theme$ = new BehaviorSubject<'light' | 'dark'>('light');
3. User session
const user$ = new BehaviorSubject<User | null>(null);
4. Notification buffer
const toast$ = new ReplaySubject<Toast>(3, 5000);
5. Boot config
const config$ = new AsyncSubject<Config>();
6. Read-only exposure
readonly state$ = this.subject.asObservable();
7. Cached HTTP
http.get('/api/x').pipe(shareReplay({ bufferSize: 1, refCount: true }));
8. Reducer store
actions.pipe(scan(reducer, initial)).subscribe(state);
9. Combined criteria
combineLatest([term$, sort$]).pipe(debounceTime(200));
10. Chained connect
source$.subscribe(subject$);
Visual
Cold Observable Against Subject
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ COLD OBSERVABLE โ
โ โ
โ sub 1 โโโบ http.get('/user') โโโบ request #1 โ
โ sub 2 โโโบ http.get('/user') โโโบ request #2 โ
โ sub 3 โโโบ http.get('/user') โโโบ request #3 โ
โ โ
โ one execution per subscriber โ
โ โ
โ SUBJECT โ
โ โ
โ subject.next(v) โโโบ sub 1 โ
โ โโโโโบ sub 2 โ
โ โโโโโบ sub 3 โ
โ โ
โ one execution, many subscribers โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Late-Subscriber Behaviour
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ALL FOUR SUBJECTS EMIT 1, 2, 3 AND COMPLETE โ
โ A NEW SUBSCRIBER THEN ARRIVES โ
โ โ
โ Subject -> complete โ
โ โ
โ BehaviorSubject -> complete โ
โ (RxJS 7: no current value after complete) โ
โ โ
โ ReplaySubject(2) -> 2, 3, complete โ
โ โ
โ AsyncSubject -> 3, complete โ
โ (the last value, then the terminal notification) โ
โ โ
โ The late subscriber is the whole difference โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The State Store Shape
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ class Store โ
โ โ
โ private readonly subject = โ
โ new BehaviorSubject<State>(initial) โ
โ โ
โ readonly state$ = subject.asObservable() โ
โ โ โ
โ โผ โ
โ consumers cannot call next โ
โ โ
โ patch(partial) { โ
โ subject.next({ ...subject.value, ...partial }) โ
โ } โ
โ โ โ
โ โผ โ
โ only the store mutates state โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Reducer Store Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ dispatch(action) โ
โ โ โ
โ โผ โ
โ Subject<Action> โ
โ โ โ
โ โผ โ
โ scan(reducer, initialState) โ
โ โ โ
โ โผ โ
โ BehaviorSubject<State> โโโบ asObservable() โโโบ reads โ
โ โ โ
โ โโโโบ .value (imperative snapshot) โ
โ โ
โ actions are events, state is a value: two subjects โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Base class | Subject<T> |
| State container | BehaviorSubject<T>(initial) |
| Bounded history | ReplaySubject<T>(n, ms?) |
| One-shot result | AsyncSubject<T> |
| Read-only view | .asObservable() |
| Synchronous read | .value on BehaviorSubject |
| Late subscriber (plain) | nothing until the next next |
| Late subscriber (behavior) | current value immediately |
| Late subscriber (replay) | buffered values immediately |
| Late subscriber (async) | last value on complete |
| Cache without writing | shareReplay({ bufferSize: 1, refCount: true }) |
| Subscription teardown | takeUntil(destroy$) |
Key takeaways:
- A
Subjectis multicast with no memory. Every subscriber only sees emissions that happen while it is attached. This is correct for events โ buttons, signals, broadcasts โ and wrong for anything that should be visible to a component that mounts late. - A
BehaviorSubjectis the default state container. It has an initial value, gives the current value to every new subscriber, and supports a synchronous.valueread. The combination of.nextwrites,.valuereads, andasObservable()exposure is the canonical pattern. asObservable()is the read/write boundary. It returns the same underlying subject but strips thenext,error, andcompletemethods, so any attempt to mutate state from outside the store becomes a compile error rather than a bug.ReplaySubjectis powerful and dangerous.ReplaySubject(n)caches the lastnemissions for every future subscriber; an unbounded one is a memory leak on a high-frequency source. Provide bothbufferSizeandwindowTimeunless there is a specific reason not to.AsyncSubjectreleases the last value only at completion. A subscriber that arrives aftercompletereceives the value synchronously; one that arrives before sees nothing until completion. It is for one-shot results that must never re-run, not for streaming.- Derive narrow slices with
distinctUntilChanged. A singleBehaviorSubject<State>feeding severalmaped observables is correct only when each derived stream deduplicates. Without it, the slice is narrow in type and wide in traffic. - The
scan-plus-BehaviorSubjectpattern closes the dispatch gap. Ascanonly runs while subscribed, so a dispatch before the first subscription is lost. Pushing the reducer output into aBehaviorSubjectinside the constructor guarantees every action becomes state.
Remember: The four classes are one class with three specific extensions, and the extension each adds is exactly one answer to “what does a late subscriber see?”. Subject gives it nothing; BehaviorSubject gives it the current value; ReplaySubject gives it the last n values; AsyncSubject gives it the last value, held until completion. Pick the class by that answer, not by whether the API happens to be convenient. Then split the state into narrow derived observables with distinctUntilChanged, hide the writer behind asObservable(), and tear down every subscription that belongs to a component’s lifetime.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!