The world of observables can be intimidating for beginners. At least it was for me. It certainly took me a while to grasp the difference between cold, hot and warm observables and I would like to share the simple example that lit the light bulb in my head.
Observables are cold by default. In a cold observable, the data producer is created when the observable has a new subscription. Hence in the example below, both subscribers have independent sets of values (1, 2, 3) emitted from the producer. Using the analogy of show streaming, a new subscriber would have to watch the show from the start irregardless if the show was live.
However if we want to emulate the live streaming behaviour of a show, we need to use a hot observable instead. This can be achieved using
connect(). As seen in the example below, only the value
2 is logged for the second subscriber since the subscription is initialised only after approximately 2 seconds.
Finally, as mentioned in this article, there is a third form of observables known as warm observables. The key difference between a hot and warm observable is that in a warm observable, the data producer only starts emitting values when the first subscription is initialised on the observable. Going back to the live streaming analogy, it means the show only starts when the first subscriber arrives. The
refCount() operators can be used to create a warm observable. As illustrated below, the value
0 is logged for the first subscriber even though it is initialised after 1 second.
Hope these would be useful for anyone getting their feet wet with observables in RxJS!