Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 346
Judah Gabriel Himango Avatar asked Aug 10 '10 14:08

Judah Gabriel Himango


2 Answers

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 :(

like image 112
Jon Skeet Avatar answered Sep 23 '22 19:09

Jon Skeet


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.

like image 45
Markus Johnsson Avatar answered Sep 23 '22 19:09

Markus Johnsson