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?
Hot observables are ones that are pushing event when you are not subscribed to the observable. Like mouse moves, or Timer ticks or anything like that. Cold observables are ones that start pushing only when you subscribe, and they start over if you subscribe again.
A typical example of a hot observable are mousemove events. The mouse moves happen regardless if someone is listening or not. When we start listening for them, we only get future events. Cold Observables on the other hand are the lazy ones.
The Subject itself is hot/shared.
While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners. Every Subject is an Observable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With