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?
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.
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);
})
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