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 changed, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With