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

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.

Tags:

Angular

Rxjs