Skip to main content

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:

ts
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 3

Because the buffer is set to 2 values.


Constructor

ts
new ReplaySubject<T>(bufferSize?, windowTime?)

Parameters:

  • bufferSize - how many values to store
  • windowTime - how long to store values

Example with time:

ts
new ReplaySubject(3, 5000)

Stores:

  • a maximum of 3 values
  • no older than 5 seconds

Difference from BehaviorSubject

TypeStores valuesInitial valueNew subscriber gets
SubjectNoNonothing
BehaviorSubject1requiredthe latest value
ReplaySubjectNnot requiredthe 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:

ts
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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.