Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set dispose action to Observable?

I know how to create an observable and assign a disposing action:

Observable.Create(o =>
{
    // o.OnNext etc.
    return Disposable.Create(() => { /* ... */ });
});

But now I produced an observable from query syntax:

var observable = from x in otherObservable
                 select x;

How to assign a disposing action to such query?

like image 314
Ryszard Dżegan Avatar asked Dec 27 '25 15:12

Ryszard Dżegan


1 Answers

If I understand correctly, you want to "chain" or "listen" whenever the subscription is disposed. One way to do this is to use the Finally operator of IObservable<T>, as such:

var ob = from x in Observable.Interval(TimeSpan.FromSeconds(1))
            select x;

// Use Finally to create an intermediate IObservable
var disposeSub = ob.Finally(() => Console.WriteLine("disposed"));

// Subscribe to the intermediate observable instead the original one
var yourSub    = disposeSub.Subscribe(Console.WriteLine);

// Wait for some numbers to print
Thread.Sleep(TimeSpan.FromSeconds(4));

// "disposed" will be written on the console at this point
yourSub.Dispose();

Hope that helps!

like image 91
cvbarros Avatar answered Dec 30 '25 03:12

cvbarros