我正在努力了解以下黄金法则(如果有的话):
什么时候使用 BehaviorSubject ?
和
什么时候使用 PublishSubject ?
它们之间的区别非常明显
科目种类繁多。对于这个特定的要求,PublishSubject 工作得很好,因为我们希望从它停止的地方继续序列。因此,假设事件 1、2、3 在 (B) 中发出,在 (A) 连接回来后我们只想看到 4、5、6。如果我们使用 ReplaySubject,我们会看到 [1、2、3]、4、 5, 6;或者如果我们使用 BehaviorSubject,我们会看到 3、4、5、6 等(来源: How to think about Subjects in RxJava (Part 1) )
我已经看到 Subject
用于两个上下文(至少),UI 上下文和侦听器上下文。
- UI 上下文(以 MVVM 为例)
For example here a BehaviorSubject
is used, and it’s clear why they use Subject
and not Observable
but I have changed the BehaviorSubject
to PublishSubject
但应用程序行为仍然相同。
- 侦听器上下文
为什么他们将 项目 字段 BehaviorSubject
而不是 PublishSubject
?
原文由 TooCool 发布,翻译遵循 CC BY-SA 4.0 许可协议
PublishSubject
和BehaviorSubject
之间的主要区别在于后者会记住最后发出的项目。因为BehaviorSubject
当你想发出states
时真的很有用。可能是因为他们希望能够使用此方法检索最后发出的项目: