DEV Community

loading...

Observables - Cold, Hot or Warm?

kengste profile image Keng Hong ・2 min read

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.

Alt Text

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 publish() and 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.

Alt Text

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 publish() and 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.

Alt Text

Hope these would be useful for anyone getting their feet wet with observables in RxJS!

Readings
https://softchris.github.io/books/rxjs/hot-n-cold-observables/

Discussion (0)

pic
Editor guide