When to Use RxJS Subject, ReplaySubject, and Behavior Subject

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.

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.

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.

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

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

Demo

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation