The use of ReplaySubject(1) vs BehaviourSubject in RxJS.
I love using the RxJS library in combination with Angular in my work. One of the things you have to do often in web applications is managing some sort of state.
To keep state I was mostly using a BehaviorSubject. The advantage of using a BehaviorSubject is that it can cache the last emitted value and emit it to new subscribers of the Observable. One of the major drawbacks of a BehaviorSubject is that you have to define an initial state to the subject. Sometimes you don’t have a logical initial value, for example because the state needs to come from the web server.
You could solve this by adding a filter to your public exposed observable, a service that does this look like this:
You have to filter out the placeholder to ensure you have no unexpected behavior because of an unexpected input. It can produce some very nasty bugs that are hard to debug. For example in an application we checked if the user was logged in and had a valid user session, when he hadn’t the user was logged out and redirected to the login page. But on a reload request to the server for the session data was received after the check if the user had a valid session which resulted in that the user was always redirected to login page instead of waiting for the session data.
The use of a ReplaySubject.
The behavior of a ReplaySubject is very similar to a behaviour subject when given the value of 1. The constructor of a ReplaySubject is given a numeric input that determines the amount of emitting values that needs to be repeated. The service has for the consumer the exact same interface and behavior will look like this:
This version doesn’t need an extra filter and no need to provide a default value. Also the compiler makes sure that after the initial value the initial value could not be inserted again, in this case undefined.
To conclude
A ReplaySubject does not have an initial state and the value is because of that not directly synchrone available by the method getValue. Both types of subjects have their pros and cons, it is good to know the existence of both types and use the right type for your scenario. Happy coding and have a nice day.
Refrences
Documentation BehaviorSubject: https://rxjs-dev.firebaseapp.com/api/index/class/BehaviorSubject
Documentation ReplaySubject: https://www.learnrxjs.io/learn-rxjs/subjects/replaysubject