Last week, we covered the difference between hot and cold Observables in RxJs.
Today, let’s talk about how we can make a cold Observable hot. Why would we want that? Say our Observable is an HTTP request we want to trigger before any component subscribes to it. We saw that Observables from the HttpClient
are cold, meaning that they only start fetching data when a subscriber comes over.
By making the Observable hot, the HTTP request would get triggered immediately. The share
operator would do exactly that for us:
Under the hood, share turns our Observable into a Subject, which can handle multiple subscribers and is hot by default.
The only problem with the above example is that the data could be emitted before any subscriber gets the chance to subscribe to that new hot Observable.
As a result, it makes more sense to use shareReplay
instead as it’s going to replay the latest value(s) to any new subscriber (just like a ReplaySubject
):
This code is much better because:
- The request is going to fire instantly before any subscription happens
- Any future subscriber will receive the same data from that original request instead of firing a new request.
You can look at this blog post for an illustration of the above operators with a code example.