rxjs: ReplaySubject vs BehaviorSubject

June 2021

BehaviorSubject: What is it?

ReplaySubject: What is it?

When should you use which BehaviorSubject and when Replay Subject?

A BehaviorSubject can be seen as the “base case”, since it’s got a simple API where you can easily fetch the last cached value.

The classic example for ReplaySubjects would of course be something where you need e.g. the last 10 values, think for example of a chat app.

Another time when ReplaySubject can be useful is in take(1)-kind of scenarios. Since a BehaviorSubject has an initial value, once you subscribe to it, you immediately get a value. With the ReplaySubject you can wait for the first value to arrive.

Example:

$userLoggedIn.pipe(take(1)).subscribe(isLoggedIn => {
  if (isLoggedIn) {
    // route to dashboard
  } else {
    // route to landing page
  }
})

If $userLoggedIn is a behavior subject initialized with null, you will get routed to the landing page. If it’s a replay subject nothing will happen until the subscriber actually gets the first value.

Here’s a full example: https://stackblitz.com/edit/replaysubject-vs-behaviorsubject

Architectural Note

However, often it is cleaner to handle such behavior with two components than with take(1).

Don’t

onAcceptPrivacy() {
  // I'm telling you, I'm sure there is a user here at this point!
  $user.pipe(take(1)).subscribe(myUser => {
    // handle accept
  })
}

Do

<ng-container *ngIf="user$ | async as user">
  <app-privacy-component [user]="user" (accept)="onAccept()">
  </app-privacy-component>
</ng-container>
Dear Devs: You can help Ukraine🇺🇦. I opted for (a) this message and (b) a geo targeted message to Russians coming to this page. If you have a blog, you could do something similar, or you can link to a donations page. If you don't have one, you could think about launching a page with uncensored news and spread it on Russian forums or even Google Review. Or hack some russian servers. Get creative. #StandWithUkraine 🇺🇦
Dear russians🇷🇺. I am a peace loving person from Switzerland🇨🇭. It is without a doubt in my mind, that your president, Vladimir Putin, has started a war that causes death and suffering for Ukrainians🇺🇦 and Russians🇷🇺. Your media is full of lies. Lies about the casualties, about the intentions, about the "Nazi Regime" in Ukraine. Please help to mobilize your people against your leader. I know it's dangerous for you, but it must be done!