When to Use RxJS Subject, ReplaySubject, and Behavior Subject

Ole Ersoy
1 min readJun 30, 2022

--

Introduction

Coming into RxJS we have a choice between various Observable types including.

  • Subject
  • BehaviorSubject
  • ReplaySubject

Subject<number>

When subscribing to aSubject we only receive values after the subscription was initiated.

const subject:Subject<number> = new Subject<number>();
subject.next(1);
subject.next(2);
subject.subscribe({
next: (v) => console.log(`Subject emitted: ${v}`)
});
subject.next(3);

So in the above case see that Subject emitted: 3 gets logged.

BehaviorSubject<number>

The BehaviorSubject caches the last value and we receive the last value upon initial subscription.

const behaviorSubject: BehaviorSubject<number> = new BehaviorSubject<number>(1);behaviorSubject.next(1);
behaviorSubject.next(2);
behaviorSubject.subscribe({
next: (v) => console.log(`BehaviorSubject emitted: ${v}`),
});
behaviorSubject.next(3);

So in the above case see that the following is logged.

  • BehaviorSubject emitted: 2
  • BehaviorSubject emitted: 3

ReplaySubject<number>

The ReplaySubject caches a specified number of emissions. In the below demo we did not specify a number, thus all the emissions are replayed.

const replaySubject: ReplaySubject<number> = new ReplaySubject<number>();
replaySubject.next(1);
replaySubject.next(2);
replaySubject.subscribe({
next: (v) => console.log(`ReplaySubject emitted: ${v}`),
});
replaySubject.next(3);

So in the above case see that the following is logged.

  • ReplaySubject emitted: 1
  • ReplaySubject emitted: 2
  • ReplaySubject emitted: 3

Demo

--

--