Reactive Programming
Continuing my intermittent series in Rx, today I take a look at Hot vs. Cold Observables in the Reactive Extensions Library.The distinction, in a nutshell, is this:
Hot observables are like a river – you can dip into them when you arrive, but whatever has moved downstream is missed. Cold observables are like a river that has been dammed – each time you subscribe or observe the dam is opened and the elements in the river are sent your way.
An example reveals this most clearly. The Return operator is a cold observable, and if it weren’t it would be totally useless. To see this clearly, put the following code into LinqPad
var input = Observable.Return(42); input.Dump();
If you have LinqPad set up with Rx (which I’ll document in an upcoming post) the output is 42
If Return were a hot observable, it would immediately return the value 42, which would go unnoticed as the Dump was not yet called. Then, when Dump was called, there would be no value to show. Oops, you missed it, it is downstream by now.
Because Return is a cold observable, the call to input.Dump() releases the value 42, and it is observed in the output.
In general, cold observables are more flexible than hot observables. When it makes sense, Rx will try to give you cold observables. Unfortunately, there is no way to tell from the signature, type or name of an operator whether it is hot or cold. You just have to look it up.