What is ReplaySubject?
Let's continue in the same format.
Briefly (as in an interview)
ReplaySubject is a type of Subject in RxJS that remembers several of the latest values and replays them to new subscribers.
The number of stored values is set in the constructor.
In detail
ReplaySubject is an extension of Subject that buffers previous values and replays them on a new subscription.
Example:
import { ReplaySubject } from 'rxjs';
const subject = new ReplaySubject<number>(2);
subject.next(1);
subject.next(2);
subject.next(3);
subject.subscribe(v => console.log(v));Result:
2
3Because the buffer is set to 2 values.
Constructor
new ReplaySubject<T>(bufferSize?, windowTime?)Parameters:
bufferSize- how many values to storewindowTime- how long to store values
Example with time:
new ReplaySubject(3, 5000)Stores:
- a maximum of 3 values
- no older than 5 seconds
Difference from BehaviorSubject
| Type | Stores values | Initial value | New subscriber gets |
|---|---|---|---|
| Subject | No | No | nothing |
| BehaviorSubject | 1 | required | the latest value |
| ReplaySubject | N | not required | the last N |
The main difference:
- BehaviorSubject = current state
- ReplaySubject = history
When ReplaySubject is used
Less often than BehaviorSubject. For example:
- caching events
- event history
- logging streams
- state rehydration
- event bus
Example of an event system:
events$ = new ReplaySubject<AppEvent>(10);An important point (often asked)
ReplaySubject can lead to memory leaks if:
- the buffer is large
- the stream is long-lived
- the values are heavy
That's why the buffer is almost always limited.
A typical follow-up question
In an interview you might be asked:
Why is BehaviorSubject used more often in Angular?
Answer: Because Angular state is usually a current value, not a history.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.