The next concept will look at is hot versus cold observables. A cold observable is basically just an observable where the data is created inside of it. So this means it won’t actually create the underlying data until something subscribes to it inside this observable.
I’m just generating a random number and then I’ll create two different subscribers. And you might intuitively think that they should get the same value.
But what happens is the random number gets generated once the subscription starts so each subscriber gets a different number.
That’s how you know you’re working with a cold observable. But you can make an observable hot by simply building that value outside of the observable itself. So here we set the random number outside the observable and then pass it in as a variable reload the page.
And then we’ll see both subscribers get the same random number that technically makes our observable hot but there is a way to do this without decoupling the data from the observable itself so we’ll put the random number back in the observable.
Then will create a new hot observable by calling publish on the cold observable. This tells it only to emit data once we called a corresponding connect method on it so we’ll build the subscriptions.
And at this point, nothing will happen then call connect on the hot observable and that will trigger these subscriptions to emit data and this time it’ll be shared between the two of them.
We can verify this by reloading the page and they should get the same random number.