BehaviorSubject与PublishSubject [英] BehaviorSubject vs PublishSubject
问题描述
我正在设法绕过有关以下方面的黄金法则(如果有的话)
I'm trying to get my head around the golden rule (if any) about:
何时使用BehaviorSubject?
When to use BehaviorSubject ?
和
何时使用PublishSubject?
When to use PublishSubject ?
它们之间的区别非常明显
The difference between them is very clear
主题很多.对于此特定要求,PublishSubject可以很好地工作,因为我们希望从上次停止的地方继续执行序列.因此,假设事件(1,2,3)在(B)中发出,在(A)重新连接之后,我们只希望看到4,5,6.如果我们使用ReplaySubject,我们将看到[1、2、3],45、6;或者如果我们使用BehaviorSubject,我们将看到3、4、5、6等.(来源:如何思考"RxJava(第1部分))
我已经看到 Subject
至少在两个上下文中使用,UI上下文和侦听器上下文.
I have seen that Subject
's are used in two contexts (at least), UI context and listener context.
- 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
but the app behavior still the same.
- 侦听器上下文
为什么他们要项目字段中的 BehaviorSubject
而不是 PublishSubject
吗?
Why they make project field a BehaviorSubject
and not PublishSubject
?
推荐答案
PublishSubject
和 BehaviorSubject
之间的主要区别在于,后者记住上一个发出的项目.因此,当您要发出状态
时,
The main difference between PublishSubject
and BehaviorSubject
is that the latter one remembers the last emitted item. Because of that BehaviorSubject
is really useful when you want to emit states
.
为什么他们将项目字段设置为BehaviorSubject而不是PublishSubject?
Why they make project field a BehaviorSubject and not PublishSubject ?
可能是因为他们希望能够使用此方法检索最后发出的项目:
Probably because they want to be able to retrieve the last emitted project with this method:
@Override public @NonNull Observable<Project> project() {
return this.project;
}
这篇关于BehaviorSubject与PublishSubject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!