预定一次性
在响应式Rx中使用ScheduledDisposable的好案例/示例是什么?
我喜欢使用CompositeDisposable和SerialDisposable ,但是您需要 ScheduledDisposable。
What is a good case/example for using the ScheduledDisposable in Reactive Rx
I like the using the CompositeDisposable and SerialDisposable, but would you need the ScheduledDisposable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 Rx 一次性组件的逻辑是,执行某种设置操作的代码可以返回一个
IDisposable
,该 IDisposable 匿名包含将在稍后阶段执行相关清理的代码。如果一致使用此模式,那么您可以将许多一次性物品组合在一起来执行单个清理操作,而无需了解要清理的内容。问题是,如果清理代码需要在某个线程上运行,那么您需要某种方式将一个线程上调用的
Dispose
编组到所需的线程 - 这就是ScheduledDisposable
的地方 主要示例是
SubscribeOn
扩展方法,它使用ScheduledDisposable
来确保“取消订阅”(即Dispose
)跑步在运行Subscribe
的同一个IScheduler
上。这对于
FromEventPattern
扩展方法很重要,例如,附加到事件处理程序或从事件处理程序分离,这些处理程序必须在 UI 线程上发生。以下是您可以直接使用
ScheduledDisposable
的示例:有点做作,但它应该显示如何使用
ScheduledDisposable
的合理示例。The logic of using the Rx disposables is that code that performs some sort of set up operation can return an
IDisposable
that anonymously contains the code that will do the associated clean up at a later stage. If this pattern is used consistently then you can compose together many disposables to perform a single clean up operation without any specific knowledge of what is being cleaned up.The problem is that if that clean up code needs to run on a certain thread then you need some way for
Dispose
called on one thread to be marshalled to required thread - and that's whereScheduledDisposable
comes in.The primary example is the
SubscribeOn
extension method which usesScheduledDisposable
to ensure that the "unsubscribe" (i.e. theDispose
) is run on the sameIScheduler
that theSubscribe
was run on.This is important for the
FromEventPattern
extension method, for example, that attaches to and detaches from event handlers which must happen on the UI thread.Here's an example of where you might use
ScheduledDisposable
directly:A little contrived, but it should show a reasonable example of how you'd use
ScheduledDisposable
.