Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good way to call subscribe inside subscribe?

I need to pass three data to one function from three different APIs:

this.service.service1().subscribe( res1 => {   this.service.service1().subscribe( res2 => {     this.service.service1().subscribe( res3 => {       this.funcA(res1, res2, res3);   });   }); }); 

Is it a good practice to subscribe inside a subscribe?

like image 830
Yashwanth Gurrapu Avatar asked Sep 13 '18 15:09

Yashwanth Gurrapu


People also ask

What is the use of subscribe?

What Does Subscribe Mean? Subscribe is an option offered by product vendors or service providers that allows customers to gain access to products or services. Most subscription-based models are paid services, which require a customer to pay a subscription fee to access and use a particular product or service.

How use JavaScript subscribe?

subscribe("HelloWorld",function(){}) . It enables developer to write out code with low coupling in JavaScript/jQuery. The subscribe() method subscribes a specific event name with an event handler, and the handler will be executed when the topic is subscribed.


1 Answers

The correct way is to compose the various observables in some manner then subscribe to the overall flow — how you compose them will depend on your exact requirements.

If you can do them all in parallel:

forkJoin(   this.service.service1(), this.service.service2(), this.service.service3() ).subscribe((res) => {   this.funcA(res[0], res[1], res[2]); }); 

If each depends on the result of the previous, you can use mergeMap (formerly known as flatMap) or switchMap:

this.service.service1().pipe(   mergeMap((res1) => this.service.service2(res1)),   mergeMap((res2) => this.service.service3(res2)) ).subscribe((res3) => {   // Do something with res3. }); 

... and so on. There are many operators to compose observables to cover lots of different scenarios.

like image 173
Mark Hughes Avatar answered Sep 25 '22 05:09

Mark Hughes