RxJS – Part 3 – Hot and Cold Observable
All posts in RxJS series:
- RxJS – Part 1 – Introduction
- RxJS – Part 2 – Observable
- RxJS – Part 3 – Hot and Cold Observable
- RxJS – Part 4 – Operators
- RxJS – Part 5 – RxJS error handling
- RxJS – Part 6 – Chat application with RxJS
Hot and cold Observable
While working with RxJS you will definitely run into these two terms – hot and cold Observable.
Hot observable produces items regardless of the subscribers. Even if no one subscribed it will produce values. Such example is mouse move event. Mouse move occurs whether someone is listening or not.
Think of a tennis game on TV that just started. You and many others are watching it live at the same time. Someone can come in after 35 minutes and start watching. But that person will be watching from the minute 35 and you have already watched 35 minutes of that game. So it has stream-like behavior and it is hot Observable.
Cold observable waits until someone subscribes to it before producing values. In this case Observer is guaranteed to see the whole sequence from start to end.
You could associate cold observable with a game of tennis that was already played and recorded. Maybe a classic game of two titans Federer – Nadal that happened at Australian Open 2017. That was 3 months ago. Anyone could watch recording of that game from first minute to the last. If I go to watch that game 10 days after someone else watched it I will still be watching it from the first moment.
Lets see some examples:
We have six values coming out of Observable: 0, 1, 2, 3, 4, 5. However, subscriber 2 subscribes after 2700 miliseconds meaning that it will start seeing values after subscriber 1 outputs 0, 1, 2.
Might not be what you expected. This is an example of cold observable. Each subscriber owns an independent execution of the Observable. Hence, these two subscribers share none of the values emitted from Observable.
You are probably wondering how we can make both subscribers see the same values at the same time.
Now that would be an example of hot observable. As you might guess it produces the following the output:
Lazy loaded hot Observable
There is another variation of hot Observable that will start producing values only when there is at least one subscriber:
Now that would be an example of hot observable that is lazily started. That is the magic that refCount() does – it ensures that observable is emitting in live (stream) mode but only once someone subscribers for first time. Even tho first subscriber subscribed only after 2.7 seconds it will get all the values – starting from 0. However, do notice that second subscriber does not get to see the first value – 0.
We saw that hot Observable produces values regardless of subscribers. And cold Observable will only start producing values only when there is at least one subscriber.
In next post we will talk about operators and see how we can easily manipulate asynchronous data in a fluid and composable way.