Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose of Observable Items as they are generated

I have an IObservable that generates items that are disposable, and it will generate a potentially infinite number of them over its lifetime. Because of this, I want to dispose of the last item each time a new item is generated, so the Using operator will not work for this. Is there a different Rx.NET operator that can accomplish this function?

like image 251
laptou Avatar asked Jun 03 '18 18:06

laptou


2 Answers

Here is a DisposePrevious operator, based on a slightly modified version of Enigmativity's solution.

/// <summary>Disposes the previous element of an observable sequence. The last
/// element is disposed when the observable sequence completes.</summary>
public static IObservable<T> DisposePrevious<T>(this IObservable<T> source)
    where T : IDisposable
{
    return Observable.Using(() => new SerialDisposable(), serial =>
        source.Do(x => serial.Disposable = x));
}

The SerialDisposable class...

Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.

like image 113
Theodor Zoulias Avatar answered Nov 15 '22 05:11

Theodor Zoulias


If you have a IObservable<IDisposable> source then do this to automatically dispose of the previous value and to clean up when the sequence ends:

IObservable<IDisposable> query =
    Observable.Create<IDisposable>(o =>
    {
        var serial = new SerialDisposable();
        return new CompositeDisposable(
            source.Do(x => serial.Disposable = x).Subscribe(o),
            serial);
    })
like image 38
Enigmativity Avatar answered Nov 15 '22 06:11

Enigmativity