Rx 中的 IConnectableObservables
有人可以解释 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短回答:
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. CallingIConnectableObservable.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 anIConnectableObservable
. This enables subscribers to subscribe to the (single) stopwatch before it starts. CallingIConnectableObservable.Connect()
starts the stopwatch. Disposing theConnect()
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.