问题
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!
回答1:
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.
回答2:
It's important to respect the original principle behind both kinds of Subjects. As in most cases, every choice should be determined by the context. Some good initial questions would be as follows:
- Do I have an initial state for my stream?
- Do I need a quick and easy
Observable/Observerengine? - Do I really need only one object that manages "next/complete/error" and subscription?
- Does the subscriber need to receive the last item emitted?
These are always good types of questions to ask to help you to decide what kind of Subject to use.
来源:https://stackoverflow.com/questions/49504713/any-downside-to-always-using-behaviorsubject-instead-of-subject-rxjs-angular