How to safely shutdown observable #2198
Replies: 1 comment 1 reply
-
The answer depends on the nature of the observable. Specifically: is it hot or cold? With a 'cold' observable, each subscription is effectively self-contains. The observable has no innate activity of its own: instead its activity is per-subscription. For example, suppose you do this: IObservable<long> intervalTimer = Observable.Interval(TimeSpan.FromSeconds(10)); This is an observable source capable of producing events every 10 seconds. But given just the code above, it does absolutely nothing. There's no activity to shut down here, because this is a cold observable: its activity is all per-subscription. You can see that the activity is per-subscription by subscribing twice, but at different times: intervalTimer.Subscribe(x => Console.WriteLine($"Subscription 1: {x}, at {DateTime.Now}"));
Thread.Sleep(TimeSpan.FromSeconds(2));
intervalTimer.Subscribe(x => Console.WriteLine($"Subscription 2: {x}, at {DateTime.Now}"));
Thread.Sleep(TimeSpan.FromSeconds(40)); Running this I see the following:
This illustrates that this observable doesn't have a single series of events that all subscribers observe: the second subscriber subscribed 2 seconds after the first, and it gets its own series of events that happen 2 seconds after the first subscriber gets its events. When the first subscriber unsubscribes, that will shut down the first stream of events. When the second subscriber unsubscribes, that will shut down the second stream of events. So there is no single, central, shared activity that can be shut down.
The observable doesn't actually need to be told to shut down. However, the logical model implied by your question does apply to hot observables. Those represent some source of events that exists independently of any subscription. As far as I can remember, there are no innately hot sources in Rx. There are sources like the You can write your own hot sources. And it will be up to you do decide how to shut those down. |
Beta Was this translation helpful? Give feedback.
-
Besides waiting for the source, timer, thread, or whatever, to stop on its own, after subscribers have been
IDisposable.Dispose()
. It is easy enough to dispose of the subscribers, but is that the only way to signal to the observable that it should also tear down, shutdown, whatever?Beta Was this translation helpful? Give feedback.
All reactions