始终使用BehaviorSubject而不是Subject(RxJs \ Angular)有什么弊端? [英] Any downside to always using BehaviorSubject instead of Subject (RxJs\Angular)?

查看:316
本文介绍了始终使用BehaviorSubject而不是Subject(RxJs \ Angular)有什么弊端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,其中部分代码库相当自由地使用BehaviorSubject.在大多数情况下,当没有初始状态或需要在第一个显式"onNext/emit"之外具有初始值时使用.

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".

我很难确定这是否有不利之处?同样如果不是,为什么每个人都不会总是只使用BehaviorSubject(即使没有参数也构造)而不是标准的Subject?

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?

提前谢谢!

推荐答案

除初始值外,BehaviorSubject与Subject完全不同:它也像ReplaySubject(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.

因此,例如,如果您想将数据存储在服务中,那么BehaviorSubject通常是一个不错的选择.另一方面,主题可能更适合向订阅者发出事件.

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;

代替

var x = 5;

但是...为什么呢?

不要发出订阅者需要努力忽略的事件.典型的Angular情况是使用您在ngOnDestroy中发出+ complete的Subject,因此您可以使用takeUntil来限制组件中的订阅.如果它是一个BehaviorSubject,那就行不通了.

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.

这篇关于始终使用BehaviorSubject而不是Subject(RxJs \ Angular)有什么弊端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆