One of the first important problems people encounter with RXJS is that of cold and hot observables. We are going to see why they exist, and how to work with them. Here, we have RXJS imported into JSbin, and we've made a clock observable which ticks every second.
When we subscribe to this observable, we see the numbers one to 10 being emitted, like this. One, and two, and et cetera. So, what happens when we do another subscription to this clock observable after four and a half seconds have passed? We set a time out, and we subscribe to this clock observable again. This time, logging out B, and the event after four and a half seconds.
So, before I hit this run button, try to guess what you would expect to see after four and a half seconds. The A subscriber sees one, then two, et cetera. Now, B kicks in, and B sees one, and two, and three, and so forth. So, B did not see events five and six, and et cetera.
Many people consider this not to be intuitive at all. They would expect that the observable has a single execution and consistency between subscribers. Why does this happen? It turns out, "An observable is analogous to a video." It is recorded, and you can watch it.
Take a look at these YouTube videos, for instance. When I hit play on a YouTube video, it starts the video's frames one by one, as you would expect. But what happens if I have the same video on another tab, and I press play after some while? Well, it also starts from the beginning, showing each frame, and these two executions are not synchronized. They are independent.
So, can you now see what happened to those videos is the same behavior that we saw here with these observables? This behavior is called cold in RXJS, and it means each subscriber owns an independent execution of that observable. That's why these two observables share none of the events from the clock.
This clock observable behaves like a video, actually, and each subscriber can watch it. But, what if we would really want subscribers to see the same event simultaneously? This is the case of a broadcasted video, for instance. Here are some live videos on YouTube, and there are multiple other viewers of these videos right now.
When I hit play on one of these videos, I will see the same frames that they are seeing, and simultaneously, like this. So, back to our code. What if we would want our clock observable to behave like a live video as well? Well, there is an RXJS operator for that, and in fact, a couple of operators, not just one.
Here, we're going to use publish operator to make it live and RefCount to make it start. So now, when we hit run, A sees one, and two, and three, and then B kicks in, and B sees five, and six, and seven, and et cetera. So now, they share the same events at the same time. This behavior is called hot in RXJS. As a recap, a cold observable is analogous to a recorded video, and a hot observable is like live video.