Rx 中的 IConnectableObservables

发布于 2024-09-01 16:50:43 字数 137 浏览 9 评论 0原文

有人可以解释 Observable 和 ConnectableObservable 之间的区别吗? Rx 扩展文档非常稀疏,我不明白 ConnectableObservable 在什么情况下有用。

此类在 Replay/Prune 方法中使用。

Can someone explain the differences between an Observable and a ConnectableObservable? The Rx Extensions documentation is very sparse and I don't understand in what cases the ConnectableObservable is useful.

This class is used in the Replay/Prune methods.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

二手情话 2024-09-08 16:50:43

简短回答:

IConnectableObservable 表示可以与多个订阅者共享的待定热可观察对象。调用 IConnectableObservable.Connect() 会导致更改为热(订阅冷源 observable)

长答案:

一个冷 observable(例如 Observable.Range) 重播每个订阅者的序列。它类似于秒表,每个订阅者都有自己的秒表。订阅者通过订阅来启动秒表,一旦观察者停止观察,秒表就停止(并重置)。

热可观察在所有订阅者之间共享序列。这类似于有一个秒表,所有订阅者都会获得相同的时间读数,无论他们何时开始观看。

IObservable.Publish 将冷 observable 转换为热 observable,但返回一个 IConnectableObservable。这使得订阅者能够在(单个)秒表开始之前订阅它。调用 IConnectableObservable.Connect() 启动秒表。处理 Connect() 返回值会停止秒表。

值得注意的是,一些可观测的源本质上是热的。例如,无论我们是否订阅鼠标事件,它们都可以触发。在这种情况下,所有可连接的可观察对象所做的就是共享单个事件订阅。

Short answer:

IConnectableObservable represents a pending hot observable that can be shared with multiple subscribers. Calling IConnectableObservable.Connect() causes the change to hot (subscribes to the cold source observable)

Long answer:

A cold observable (like Observable.Range) replays the sequence for each subscriber. It's analagous to a stopwatch, where every subscriber is given their own stopwatch. The subscriber starts the stopwatch by subscribing, and the stopwatch stops (and resets) once the observer stops observing.

A hot observable shares the sequence between all subscribers. It's analagous to there being one stopwatch and all subscribers are given the same time readout, regardless of when they started watching.

IObservable.Publish converts a cold observable into a hot observable, but returns an IConnectableObservable. This enables subscribers to subscribe to the (single) stopwatch before it starts. Calling IConnectableObservable.Connect() starts the stopwatch. Disposing the Connect() return value stops the stopwatch.

It's worth noting that some observable sources are hot by nature. For example, mouse events can fire regardless of whether we are subscribed to them. All a connectable observable would do in this scenario is a share a single event subscription.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文