Quantcast
Channel: My musings on .Net Technology » Rx
Viewing all articles
Browse latest Browse all 5

Reactive Extension SerialDisposable gottcha

$
0
0

MSDN defines SerialDisposable as “a disposable whose underlying disposable can be swapped for another disposable which causes the previous underlying disposable to be disposed.”, but it does not state or make it obvious that former disposable i.e. the one that is swapped out, should never be explicitly disposed; otherwise the new disposable will be disposed right away when swapped (See the setter in the screenshot below), therefore unsubscribing the new subscription.

To understand better, try changing line 5 to “serialDisposable.Disposable.Dispose();” and see the difference

  1. var serialDisposable = new SerialDisposable();
  2.             serialDisposable.Disposable = Observable.Range(1, 100, Scheduler.NewThread).Repeat().Sample(TimeSpan.FromMilliseconds(500)).Subscribe(Console.WriteLine, () => Console.WriteLine(“Done”));
  3.             Console.WriteLine(“Press any key to unsubscribe”);
  4.             Console.ReadKey();
  5.             serialDisposable.Dispose();
  6.             Console.WriteLine(“Disposed … Resubscribing …”);
  7.             serialDisposable.Disposable = Observable.
  8.                 Range(1000, 100, Scheduler.NewThread).
  9.                 Repeat().Sample(TimeSpan.FromMilliseconds(500)).
  10.                 Subscribe(Console.WriteLine);
  11.             Console.WriteLine(“You should not see numbers bigger than 100″);
  12.             Console.ReadKey();



Viewing all articles
Browse latest Browse all 5

Trending Articles