Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any downside to always using BehaviorSubject instead of Subject (RxJs\Angular)?

Tags:

angular

rxjs

I am working on a project in which portions of the code-base are using BehaviorSubject quite liberally. In most cases being used when there is no initial state, or a need to have an initial value outside of the first explicit "onNext/emit".

I am having a hard time determining if there is any downside to this? Also if not, why wouldn't everyone just always use BehaviorSubject (even constructed without a parameter) as opposed to a standard Subject?

Thanks in advance!

like image 287
iHazCode Avatar asked Mar 27 '18 05:03

iHazCode


1 Answers

A BehaviorSubject is quite different from a Subject other than the initial value: it also acts like a ReplaySubject(1). This means that new subscribers will always get the last (or initial) value emitted synchronously. With a Subject, you only get the emissions that happen after you subscribed.

Hence, if you want to, say, store data in a service, a BehaviorSubject is typically a good choice. A Subject on the other hand might be better suited to emit events to subscribers.

In other words, use a Subject when you don't care about the past ever.


As far as the initial value goes, regardless of those effects: if you don't need one, don't use one. Why? Because. I mean you can also always write

var x;
x = 5;

instead of

var x = 5;

But... why would you?

Don't emit events that the subscriber needs to put effort into ignoring. A typical Angular case is using a Subject which you emit + complete in ngOnDestroy so you can use takeUntil to limit subscriptions in the component. If it was a BehaviorSubject, it just wouldn't work.

like image 93
Ingo Bürk Avatar answered Oct 08 '22 10:10

Ingo Bürk