gpt4 book ai didi

android - BehaviorSubject 与 PublishSubject

转载 作者:可可西里 更新时间:2023-11-01 18:57:36 25 4
gpt4 key购买 nike

我正在努力了解以下黄金法则(如果有的话):

When to use BehaviorSubject ?

When to use PublishSubject ?

它们之间的区别很明显

There are many kinds of subjects. For this specific requirement, a PublishSubject works well because we wish to continue the sequence from where it left off. So assuming events 1,2,3 were emitted in (B), after (A) connects back we only want to see 4, 5, 6. If we used a ReplaySubject we would see [1, 2, 3], 4, 5, 6; or if we used a BehaviorSubject we would see 3, 4, 5, 6 etc. (source : How to think about Subjects in RxJava (Part 1))

我已经看到 Subject(至少)在两个上下文中使用,UI 上下文和监听器上下文。

  • UI 上下文(以 MVVM 为例)

例如here使用了 BehaviorSubject,很清楚为什么他们使用 Subject 而不是 Observable 但我已将 BehaviorSubject 更改为PublishSubject 但应用行为仍然相同。

  • 听众背景

为什么他们制作 project字段 BehaviorSubject 而不是 PublishSubject ?

最佳答案

PublishSubjectBehaviorSubject 之间的主要区别在于后者会记住最后发出的项目。因为 BehaviorSubject 在您想要发出 states 时非常有用。

Why they make project field a BehaviorSubject and not PublishSubject ?

可能是因为他们希望能够使用此方法检索最后发出的项目:

@Override public @NonNull Observable<Project> project() {
return this.project;
}

关于android - BehaviorSubject 与 PublishSubject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50020345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com