Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rx Disposing a subscription

What is the recommended way to dispose of subscriptions that are created in a loop? In the following contrived example I'm generating subscriptions in a for loop and adding them to a List and disposing them explicity by for eaching over the List This seems a bit smelly to me and I'm thinking that there has to be a cleaner way to clean up the subscriptions unless the GC disposes them when it runs. Do I need to explicity Dispose the subscriptions?

class Program
{
    static void Main(string[] args)
    {
        Func<int, IEnumerable<int>> func = x =>
        {
            return Enumerable.Range(0, x);
        };

        List<IDisposable> subsriptions = new List<IDisposable>();
        for (int i = 1; i < 10; i++)
        {
            var observable = func(i).ToObservable().ToList();
            var subscription = observable.Subscribe(x => Console.WriteLine(x.Select(y => y.ToString()).Aggregate((s1, s2) => s1 + "," + s2)));
            subsriptions.Add(subscription);
        }
        Console.ReadLine();
        subsriptions.ForEach(s => s.Dispose());
    }
}
like image 866
Abhijeet Patel Avatar asked May 19 '11 04:05

Abhijeet Patel


1 Answers

Subscriptions do not need to be disposed if the source completes. In your example, you would only dispose the subscription if you wanted to stop enumerating the Range before it was finished.

Even in that situation, it's more common to dispose of subscriptions by using an operator that terminates the subscription as part of its design like Take, TakeWhile, TakeUntil.

If you do want to combine several IDisposable subscriptions, CompositeDisposable is designed to do exactly that:

CompositeDisposable subsriptions = new CompositeDisposable();

subscriptions.Add(Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe());
subscriptions.Add(Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe());
subscriptions.Add(Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe());

subscriptions.Dispose();
like image 72
Richard Szalay Avatar answered Sep 18 '22 00:09

Richard Szalay