Michal Majewski Michal Majewski - 1 month ago 30
Javascript Question

Rxjs - switchMap to http changes observable character from hot to cold

Can somebody explain me why below code triggers request to server three times? if i were subscribing directly to http.get() i know that its cold observable so it will result callin server 3 times and i need to use .share() to avoid that. but why the same behavior when i am subscribing to subject which is hot.. weird:

let testTrigger = new Subject<any>();


let testTask$ = testTrigger.switchMap(()=> this.restClient.get('onet'));

testTask$.subscribe(console.log.call(console));
testTask$.subscribe(console.log.call(console));
testTask$.subscribe(console.log.call(console));
testTrigger.next(1);

Answer

In fact most operators would do the same. i.e. if obs is hot, then obs.op is in general cold. A few operators also returns hot observables (groupBy for example). In the end you need to read the documentation or test to see the nature of the observable you have in your hand.

For more details you can have a look at Hot and Cold observables : are there 'hot' and 'cold' operators?.