Search code examples
c#system.reactiverx.net

subject.Dispose() vs subject.OnCompleted()


What's the difference between .Dispose() and .OnCompleted() call on a Subject ?

Usually i dispose subscription to stop listening an observable and complete a subject when it's no longer useful anywhere on the code,


Solution

  • According to the documentation of the Subject<T>.Dispose method:

    Releases all resources used by the current instance of the Subject<T> class and unsubscribe all observers.

    It seems that attempting to do anything with a Subject after disposing it, results to an ObjectDisposedException. You can't Subscribe to a disposed Subject for example. Any subscriptions that are active at the time the Subject is disposed, will be disposed too, and the unsubscribed observers will not receive OnCompleted notifications.

    On the contrary a subject that has been completed by calling its OnCompleted method can still be subscribed at any time, in which case the subscribed observer will receive instantly an OnCompleted notification. Of course if the completed subject is one of the buffered types like the ReplaySubject, then the observers will receive a number of OnNext notifications before the final OnCompleted.

    Personally I would consider calling Dispose to a ReplaySubject that is about to be discarded, in order to accelerate the recovery of the RAM used by its internal buffer. I am not sure if this would make any difference though, since the Dispose is generally supposed to release unmanaged resources, and the memory used by the buffer is most probably managed.