The Four Subject Types in RxJS
Subject, BehaviorSubject, ReplaySubject and AsyncSubject differ in what late subscribers see and in how completion or an error ends their stored behavior.
A Subject isn’t an Observable with a next() method bolted on. It’s a different model: hot instead of cold, multicast instead of unicast, with a lifecycle that keeps running whether anyone is listening or not. If you only use it as a convenient shortcut to finally push values into a stream yourself, you get timing behavior you never asked for.
So before you choose between the four types, there is another question: Is a stream worth it here at all, or would a simpler model do the job just as well? If you skip that question, you build reactivity where a variable or a promise would have been enough. If you ask it and answer yes, you have exactly one decision left to make – and made correctly, it saves you a whole class of timing bugs that are hard to reproduce and expensive to debug.
A Subject is the building block you use to call into the reactive world from imperative code. A normal observable isn’t built for that – it describes a source you subscribe to, and it only starts its work then, lazily, anew for each subscription. This is exactly where the Subject enters the stage. And as soon as this bridge is in place, the next question follows: Why are there four variants of it? The short answer: they differ in memory. The long answer is this article.
If you want to refresh the basics of the push model, you’ll find them in RxJS: Push and Pull. Here I assume that you’re familiar with Observable and Subscription, and I focus on the decision behind them and on the Subjects themselves. This covers RxJS 7.
Is reactivity worth it here at all?#
Before I choose between the four types, I ask a question first: Does this place need a stream at all? Reactivity isn’t an end in itself. It’s a model with costs. A Subject comes with a lifecycle you have to take care of – subscriptions you unsubscribe again, buffers that hold memory, timing you have to keep in your head. These costs pay off, but not everywhere.
For a single value that is computed once and then read, a variable is enough. For a single asynchronous operation with exactly one result, a promise is the simpler and more familiar tool. For a finished list that is fully available, an array with the usual methods will do. Setting up a stream in all these cases makes the code more expensive without giving anything back – you take on the subscription lifecycle and get nothing in return that the simpler model wouldn’t have delivered too.
Reactivity pays off the moment three things come together: values arrive spread out over time, not all at once; there is more than one party interested in the same values; and you want to combine, filter, cancel or merge these values instead of just receiving them once. A click stream, a WebSocket, a state shared by several components – these are the cases where a tangle of variables and callbacks quickly gets confusing and a stream takes out the friction.
The upfront question costs nothing and keeps the amount of reactive code small. Where reactivity carries weight, it plays to its strengths, and the rest stays simple. Only when the answer is yes does the second question become relevant, the one this article is about: what memory the stream should have for late subscribers.
A Subject is both at once#
The key sentence about Subjects is already in the class definition: Subject<T> extends Observable<T> and at the same time implements the Observer interface. That means a Subject is Observable and Observer in a single instance. You can subscribe to it like any Observable – and you can feed values into it through next, error and complete like into an Observer.
import { Subject } from 'rxjs';
const subject = new Subject<number>();
// als Observable: abonnieren
subject.subscribe((value) => console.log('received', value));
// als Observer: Werte hineingeben
subject.next(1);
subject.next(2);
subject.complete();
This dual role has an important consequence. A plain observable is cold and unicast: every subscriber gets its own execution, and the code inside the observable runs again for each subscription. A Subject, on the other hand, is multicast. It keeps a list of its subscribers, and when next is called, the same value goes to all of them at the same time. There is one source and many receivers.
flowchart LR
P["Source<br/>next / error / complete"] --> S(("Subject"))
S --> A["Subscriber A"]
S --> B["Subscriber B"]
S --> C["Subscriber C"]The second central trait follows from this: Subjects are hot. Values flow regardless of whether anyone is listening. If I call subject.next(1) before any subscriber exists, that value is simply gone with a plain Subject. It was emitted, but nobody was there to receive it. Exactly this point – what happens to values that flowed before a subscription – is what separates the four types.
The four types and their memory#
Before we go into the details, here’s the overview. All four inherit from Subject, and all four are hot and multicast. The difference lies in what a subscriber sees when it arrives late:
- A
Subjecthas no memory. If you subscribe after anext, you missed the value. Only what flows from the moment of subscribing arrives. - A
BehaviorSubjectremembers the last value and needs an initial value. Every new subscriber immediately gets the current state – ideal for the “current state” case. - A
ReplaySubjectbuffers the last n values and replays them to every new subscriber, even aftercomplete. - An
AsyncSubjectemits only the very last value, and only oncecompletehas been called.
The list only describes next and complete. An error ends each of these streams. After that, a BehaviorSubject no longer delivers a last value and an AsyncSubject no final result; a ReplaySubject still replays its buffer and then reports the error. These terminal signals are therefore just as much part of the choice as the behavior for late subscriptions.
Let’s look at each type with a small timing example, because timing is exactly what matters.
Subject – the forgetful one#
Let’s start with the plain Subject. It has no memory. To make this visible, we subscribe at different times and watch who gets what.
import { Subject } from 'rxjs';
const subject = new Subject<number>();
subject.next(1); // niemand hört zu -> verloren
subject.subscribe((v) => console.log('A', v));
subject.next(2);
subject.subscribe((v) => console.log('B', v));
subject.next(3);
// Ausgabe:
// A 2
// A 3
// B 3
The value 1 vanished because no subscriber existed when it was emitted. Subscriber A joins before the 2 and therefore sees 2 and 3. Subscriber B only arrives after the 2 and sees only 3. That’s not a bug. That’s the definition. A Subject is a pure distributor for the moment.
What is that good for? For real events where the past doesn’t matter. A click, a WebSocket frame, a command that gets triggered. If you aren’t listening when the event happens, you simply didn’t witness it – and that’s perfectly fine.
BehaviorSubject – the state holder#
Now the type I see and recommend most often in practice: the BehaviorSubject. It differs in two ways. First, its constructor needs an initial value – you can’t create a BehaviorSubject without a defined starting state. Second, it always remembers the last emitted value and delivers it synchronously to every new subscriber.
import { BehaviorSubject } from 'rxjs';
const state$ = new BehaviorSubject<number>(0); // Initialwert Pflicht
state$.subscribe((v) => console.log('A', v)); // A bekommt sofort 0
state$.next(1);
state$.subscribe((v) => console.log('B', v)); // B bekommt sofort 1
state$.next(2);
// Ausgabe:
// A 0
// A 1
// B 1
// A 2
// B 2
Subscriber B joins late and still isn’t left empty-handed. On subscribing, it immediately receives the current value 1 and then the rest. That’s exactly what makes the BehaviorSubject the standard tool for state. A state always has a current value, and whoever asks for it wants that value – not the prospect of learning something at the next next.
A practical bonus: the BehaviorSubject offers synchronous access to the current state through getValue() and the value property, without subscribing.
const counter$ = new BehaviorSubject<number>(0);
counter$.next(42);
console.log(counter$.getValue()); // 42
console.log(counter$.value); // 42
If you have ever worked with streams as a data source in RxJS in React, you know the situation: a component mounts and subscribes, and of course it should be able to show something right away. A BehaviorSubject guarantees exactly that.
A detail that is easy to overlook: after complete(), a BehaviorSubject no longer sends its last value to new subscribers. It then only delivers the complete signal. So the current value is only available as long as the stream is active.
ReplaySubject – memory with a buffer#
The BehaviorSubject remembers exactly one value. Sometimes you need more history. That’s what the ReplaySubject is for. Its constructor takes a buffer size and replays these last n values to every new subscriber.
import { ReplaySubject } from 'rxjs';
const replay$ = new ReplaySubject<number>(2); // die letzten 2 Werte puffern
replay$.next(1);
replay$.next(2);
replay$.next(3);
replay$.subscribe((v) => console.log('late', v));
replay$.next(4);
// Ausgabe:
// late 2
// late 3
// late 4
The late subscriber gets 2 and 3 after the fact – the two last buffered values – and then 4 live. The value 1 drops out of the buffer, because the buffer only has two slots.
Two properties make the ReplaySubject special. First, besides the buffer size there is an optional time window parameter: new ReplaySubject<number>(bufferSize, windowTime). With it, only values that flowed within the last x milliseconds are replayed. Second – and this is the big difference from the BehaviorSubject – the ReplaySubject still replays its buffer after complete().
const cache$ = new ReplaySubject<number>(3);
cache$.next(10);
cache$.next(20);
cache$.next(30);
cache$.complete();
// nach complete abonnieren
cache$.subscribe((v) => console.log('after complete', v));
// Ausgabe:
// after complete 10
// after complete 20
// after complete 30
This works well as a small cache: a result is produced once and then delivered again to everyone who asks later. Be careful with a buffer size of Infinity, though – that’s the default. A ReplaySubject without a size remembers every value it has ever emitted and grows without limit. In long-lived streams, that’s a source of memory leaks. That’s why I set the buffer size deliberately.
AsyncSubject – only the final result#
The fourth type is the most idiosyncratic. The AsyncSubject emits only a single value – the last one – and only when complete() is called. As long as no complete arrives, there’s nothing.
import { AsyncSubject } from 'rxjs';
const async$ = new AsyncSubject<number>();
async$.subscribe((v) => console.log('result', v));
async$.next(1);
async$.next(2);
async$.next(3);
async$.complete(); // erst jetzt wird emittiert
// Ausgabe:
// result 3
The AsyncSubject doesn’t care about the intermediate values 1 and 2. It only remembers the latest one, and on complete it passes that one on to all subscribers – including those who only subscribe after the complete. The behavior is deliberately reminiscent of a promise: a computation that runs and delivers exactly one result at the end.
The most common pitfall here is the missing complete. Without this call, the AsyncSubject never emits. The mistake looks harmless and still costs half an hour: the values flowed, the console stays empty, and at first you look everywhere – except at the missing completion.
Which one when – the decision#
Let’s sum up the choice. The question you should always ask is: What should a subscriber see that arrives late?
- It’s about an event, and the past is irrelevant? Subject.
- It’s about a current state that must always be available? BehaviorSubject.
- New subscribers should receive the last n values or a time window after the fact? ReplaySubject.
- All that matters is a single final result after completion? AsyncSubject.
In practice, two of them dominate. BehaviorSubject for state, Subject for events. ReplaySubject and AsyncSubject are special tools for specific needs.
Two pitfalls from practice#
Finally, the two mistakes I run into most often. Both are easy to avoid once you have seen them.
The first is mixing up Subject and BehaviorSubject for state. You build a service that holds a current value but use a plain Subject. Then a component mounts, subscribes – and stays empty, because the last next already happened. The bug shows up as “sometimes the value is there, sometimes it isn’t,” depending on timing. For state, the rule is: always BehaviorSubject, so there is a defined current value.
The second pitfall is subtler and affects the architecture: exposing Subjects everywhere instead of plain Observables. If I expose a Subject as a public property, anyone outside can call next() or complete() on it. That breaks encapsulation – any place in the code can interfere with the stream or complete it. The clean solution is a private Subject and a public Observable through asObservable():
import { Subject, Observable } from 'rxjs';
interface Command {
type: string;
}
class CommandBus {
private commandsSubject = new Subject<Command>();
// nach außen nur lesbar
readonly commands$: Observable<Command> = this.commandsSubject.asObservable();
dispatch(command: Command): void {
this.commandsSubject.next(command);
}
}
From the outside, you can subscribe to commands$, but you can’t write into it. The next runs exclusively through the controlled dispatch method. That’s the same principle that also carries RxJS in Node.js: events flow in through a defined interface and back out through subscribable observables. A Subject as the engine inside, an Observable as the facade outside.
Don’t get me wrong: Subjects aren’t an anti-pattern. They are the right tool whenever you have to write into a stream from imperative code. The Subject itself should just stay inside wherever possible.
Conclusion#
A Subject is Observable and Observer in one and multicasts the same values to all its subscribers. It’s hot – values flow whether anyone is listening or not. The four variants differ in only a single dimension: their memory for subscribers that arrive late. No memory for the Subject, the last value for the BehaviorSubject, the last n values for the ReplaySubject, the final result after completion for the AsyncSubject.
If you make this one question – what does a late subscriber see? – a habit, the choice becomes almost automatic. And if you ask the question before it – is a stream worth it here at all? – you keep the amount of reactive code limited to what actually benefits from it. The outcome is unspectacular and useful for exactly that reason: you settle on the right type faster, a whole class of timing bugs never comes into being, and the data flow stays under control where it originates – behind Observables on the outside, with a Subject as the engine inside. And where a variable, a promise or an array is enough, that’s what it stays. Reactivity is the tool for values over time and many receivers, not the default for every value.
Further reading#
Revised and translated from German with the help of AI.