Understanding hot vs cold Observables

Photo by Emily Campbell on Unsplash

When the data is produced by the Observable itself, we call it a cold Observable. When the data is produced outside the Observable, we call it a hot Observable.

We jumped a few steps ahead, so let’s go back and dive in.

Cold Observables

So, we call an Observable “cold” when the data is produced inside the Observable. As you might have read in my previous article, Observables are lazy. Observables are lazy in the sense that they only execute values when something subscribes to it. For each subscriber the Observable starts a new execution, resulting in the fact that the data is not shared. If your Observable produces a lot of different values it can happen that two Observables that subscribe at more or less the same receive two different values. We call this behaviour “unicasting”. To demonstrate this:

;

Hot Observables

Yes, it is that easy. An Observable is cold when data is produced inside the Observable and the Observable is hot when the data is produced outside the Observable. As we just saw the hot Observable is able to share data between multiple subscribers. We call this behaviour “multicasting”.

Is one better than the other?

Well, that depends on the usecase. A cold Observable is usually fine, unless:

  • You want to make sure multiple subscribers get the same data.
  • Your creating a new instance of something on each Observable execution, let’s say a websocket connection. You don’t want to create a new connection for each subscriber, but instead just share it to all the subscribers. Moving the instantiation of the connection outside the Observable will make it hot and fixes this.

Conclusion

I hope this article helps you understand better how Observables work and what the implications are of producing data inside (cold) or outside (hot) your Observable. If you want to dive deeper into rxjs i recommend you to read one of my other articles about Subjects or BehaviorSubjects, ReplaySubjects and AsyncSubjects.

Looking for a job in Amsterdam?

I work for Sytac as a Senior front-end developer and we are looking for medior/senior developers that specialise in Angular, React, Java or Scala. Sytac is a very ambitious consultancy company in the Netherlands that works for a lot of renowned companies in banking, airline, government and retail sectors. You can think of companies like ING, KLM, Deloitte, Ahold Delhaize, ABN AMRO, Flora holland and many more.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store