1

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);
user3743222
  • 18,345
  • 5
  • 69
  • 75

2 Answers2

2

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?.

Community
  • 1
  • 1
user3743222
  • 18,345
  • 5
  • 69
  • 75
2

Change your code to:

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

This way all subscriptions will share the same pipe. I guess that when you subscribe you trigger the mapping (hence the http call).

Meir
  • 14,081
  • 4
  • 39
  • 47