Hot vs Cold Observables

5.1k views Asked by At

In RxJS hot observables are observables which use an external producer, but a cold observable use a local producer (see e.g. RxJS Hot vs Cold Observable by Ben Lesh).

Angular HttpClient.post uses cold observables to send data and repeats whenever you make a call.

Is there any way in Angular to know whether a specific method uses a hot or cold observable?

2

There are 2 answers

4
Pace On BEST ANSWER

No. Documentation is the safest bet. Also, I disagree with @martin's comment, it absolutely does matter. You need to be careful with cold observables to avoid resubscribing and reissuing expensive operations (e.g. by using multicasting or saving off the result to a subject).

You also have to rely on the documentation to know when/how an observable completes. For example, you don't need to ever worry about unsubscribing from HttpClient.post because you know it will complete. However, if you're using some kind of wrapper around HttpClient which serves requests via a cached Subject you might not complete anymore. Every component will generate a new subscription and, after the component is destroyed, that subscription will be a reference from the Subject to the component so the component won't be garbage collected and you will end up with a memory leak.

There is no way to programmatically know what kind of Observable you've subscribed to, whether it will complete or not.

In general this is managed both by being smart about completing your observables and by using tools like takeUntil or Subscription to clean up subscriptions to long running non-completing observables or expensive observable workloads.

*EDIT: Actually, to clarify, you need to be careful with all observables, not just cold observables. Hot observables can generate expensive workloads too.

*EDIT2: Update example removing ActivatedRoute as those observables are completed when the component is destroyed.

0
tero17 On

An Observable can have 2 behaviors:

a) when a subscriber subscribe to it, the subscriber receive a set of data. For receiving new data, you need to subscribe again to it.

b) when a subscriber subscribe to it, the subscriber receive data continuously (when data stream change). For receiving new data, you don't need to subscribe again to the observable.

In the case a) we speak about a COLD Observervable;

In the case b) we speak about a HOT Observervable;

check this article