Rx - unsubscribing from events
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");
Now I want to listen for a particular property c开发者_开发百科hanged, and if .Progress == 100, unsubscribe:
eventStream
.Where(e => myFoo.Progress == 100)
.Subscribe(OnFooFinished);
How can I unsubscribe when Progress == 100? If I add a .Take(1) call after the .Where clause, would that automatically unsubscribe?
One option is to use return value of Subscribe
:
IDisposable subscription = eventStream.Where(e => myFoo.Progress == 100)
.Subscribe(OnFooFinished);
...
// Unsubscribe
subscription.Dispose();
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 :(
You could use the TakeWhile method:
eventStream.TakeWhile(e => myFoo.Progress != 100);
TakeWhile will dispose the underlying observable sequence when its predicate returns false, you will not have to call dispose manually.
精彩评论