本文介绍了Rx - 取消订阅事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 INotifyPropertyChanged 对象,Foo.我使用 Rx 的 FromEvent 方法将 Foo 变成可观察的事件流:

I have an INotifyPropertyChanged object, Foo. I turn Foo into an observable stream of events using Rx's FromEvent method:

var myFoo = new Foo();
var eventStream = Observable.FromEvent<PropertyChangedEventArgs>(myFoo, "PropertyChanged");

现在我想监听某个特定属性的变化,如果 .Progress == 100,取消订阅:

Now I want to listen for a particular property changed, and if .Progress == 100, unsubscribe:

eventStream
   .Where(e => myFoo.Progress == 100)
   .Subscribe(OnFooFinished);

当 Progress == 100 时如何取消订阅?如果我在 .Where 子句之后添加一个 .Take(1) 调用,会自动取消订阅吗?

How can I unsubscribe when Progress == 100? If I add a .Take(1) call after the .Where clause, would that automatically unsubscribe?

推荐答案

一种选择是使用 Subscribe 的返回值:

One option is to use return value of Subscribe:

IDisposable subscription = eventStream.Where(e => myFoo.Progress == 100)
                                      .Subscribe(OnFooFinished);

...

// Unsubscribe
subscription.Dispose();

怀疑使用Take(1)确实会取消订阅,而且它可能对你来说更整洁.稍微看了一下,我很确定这取消订阅,因为它会触发已完成"消息,通常会自动取消订阅.我目前没有时间确定这一点,恐怕:(

I suspect that using Take(1) would indeed unsubscribe though, and it may be neater for you. Having looked at it a bit, I'm pretty sure this would unsubscribe, as it'll fire the "completed" message, which generally unsubscribes automatically. I don't have time to check this for sure at the moment, I'm afraid :(

这篇关于Rx - 取消订阅事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 05:39