SerialDisposable<T>

05 May 2015

Reactive Extensions includes a super useful class called SerialDisposable. The idea is you can assign any IDisposable to it and it automatically disposes of any previously assigned value. Suppose, for example, you have a need to create a UIPopoverController whenever some user interaction occurs:

privatereadonlySerialDisposablepopoverDisposable=newSerialDisposable();privateUIPopoverControllersearchPopover;privateUIPopoverControllerSearchPopover{get{...}set{...}}// elsewhere in the codesomeUserInteractionObservable.Select(_=>newUIPopoverController(...)).Subscribe(x=>{popoverDisposable.Disposable=x;this.SearchPopover=x;});

Here we ensure that any previously created UIPopoverController is disposed of by assigning the newly created one to the Disposable property of our SerialDisposable. But notice how we also assign the same value to our SearchPopover property. That’s because SerialDisposable.Disposable is of type IDisposable. That is, by storing our UIPopoverController inside a SerialDisposable, we’ve lost some compile-time type information.

OK, so the example is contrived and incomplete but you get the point.

When faced with this situation of either doubling-up on backing fields versus sprinkling the code with casts, I figured I’d just create a generic SerialDisposable<T> class instead:

I’ve been pondering as well whether it would be a Good Idea™ to have SerialDisposable<T> also implement IObservable<T>, where each instance assigned to the Disposable property ticks the observable. As yet, the jury’s out.