Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompositeDisposable - Deterministic order?

This question references the CompositeDisposable class in the System.Reactive.Disposables namespace.

Is the order in which the CompositeDisposable calls Dispose on its members deterministic?

The following experiment yields the list ['a', 'b'], but I don't see anything in the documentation that guarantees a certain order.

var result = new List<char>();
var disposable = new CompositeDisposable(
    Disposable.Create(() => result.Add('a')),
    Disposable.Create(() => result.Add('b')));
disposable.Dispose();
like image 871
Timothy Shields Avatar asked Jul 15 '14 18:07

Timothy Shields


2 Answers

Internally CompositeDisposable uses the following field to store the disposables:

private List<IDisposable> disposables;

It uses the list .Add(...) method to add items to the end of the list. When adding items via the constructor the list is instantiated with the disposables in order.

It then uses a simple foreach loop over the disposables when disposing.

So you can be confident that the current implementation will dispose of them in order. You could also make an intelligent guess that they wouldn't change this behaviour even if they changed the implementation in the future otherwise it would be a breaking change.

like image 181
Enigmativity Avatar answered Sep 18 '22 22:09

Enigmativity


AFAIK the order is not documented. Peeking at the implementation shows it disposes them in the order they are added. But since it is not documented I guess you cannot depend upon it.

like image 40
Brandon Avatar answered Sep 19 '22 22:09

Brandon