rxSwift 中的 observable 和 subject 有什么区别

What are the differences between observable and subject in rxSwift

observable 和 subject 有什么区别。 当我定义一个可观察类型变量时。它可以发出 onNext、onComplete、onDispose。但是主题可以做同样的事情。什么时候应该使用observable,什么情况下应该使用subject?

我认为并且根据我对这两个主题的了解,我可以这么说,

Observables

  • Observable(Rx 的基础部分)是具有一些特殊功能的序列。最重要的特性是异步的。 Observable 会产生一些事件(即 onNext、onError、onCompleted),这些事件称为发射。事件包含一些值(即 Int、Bool、Array 或自定义类型)。

科目

  • 简单的observable只能发出可以订阅的事件。但是如果我们想在当前可观察对象(也称为自我观察者)上增加一些值怎么办?所以我可以简单地说,作为 observableobserver 的东西被称为 subjects.

为了理解它们之间的区别,我们应该提到 Observable 是:

In ReactiveX an observer subscribes to an Observable. Then that observer reacts to whatever item or sequence of items the Observable emits. This pattern facilitates concurrent operations because it does not need to block while waiting for the Observable to emit objects, but instead it creates a sentry in the form of an observer that stands ready to react appropriately at whatever future time the Observable does so.

换句话说,observable是数据生产者(负责发布被观察的通知)

实际上,Subject 是一种特殊类型的 Observable(您仍然可以像订阅任何其他 Observable 一样订阅消息) :

A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items.

但是主题是可观察者和观察者的表示 - 正如文档中提到的那样,这意味着主题可能是 数据生产者 (负责将通知发布到被观察或数据消费者(负责接收通知)。

:为了检查主题的类型,您可能需要检查:RxSwift Subject Types.

你得到了几个解释 Observables 和 Subjects 之间区别的答案,但没有人回答你的第二个问题...

When should I use observable and in what case should I use subject?

这是对这个问题的一个很好的答案,虽然很复杂: http://davesexton.com/blog/post/To-Use-Subject-Or-Not-To-Use-Subject.aspx

TL;DR 就是这个。尽可能使用 Observable,必要时使用 Subject。

只要您需要一个热门的可观察对象并且还没有可使用的可观察对象,您就可以使用 Subject。例如,RxCocoa 广泛使用 Subjects 来为您创建与特定 UI 元素相关联的可观察对象。它们主要用于将非 Rx 代码桥接到 Rx 代码并将生产者连接到消费者,而出于某种原因必须首先创建消费者。