Search code examples
rxjsrxjs-observables

RXJS Nested dependant subscriptions


I'm trying to wrap my head around using Observables. But I'm struggling. I've googled this for a while, and i can't really decide if the examples i see do what i try to do.

I'll try to explain it, so maybe someone can explain it to me.

I have this http endpoint, to which i post a JSON object. The backend stores it, and returns the persisted object, with an id. Then based on what i get in response here, i need to update the object by calling http endpoint number two.

Let's say service1 is the post or creating the object and service2 is for updating it. I would then do the following:

service1.create(theNewObject).subscribe(response => {
   service2.update(response).subscribe(secondResponse => { console.log(secondResponse) })
})

I am pretty sure that this does what I'm trying to do, but I've read somewhere that doing a subscribe inside another subscribe is not the way to do it.

So my question is.. what do do here, if i can't do it this way?

This is hard to wrap my head around..

Thanks in advance!


Solution

  • you use what's known as a higher order operator:

    import {switchMap} from 'rxjs/operators'; // import the operator
    
    service1.create(theNewObject).pipe(
      switchMap(response => service2.update(response))
    ).subscribe(secondResponse => { console.log(secondResponse) })
    

    higher order operators generally involve an outter and inner observable. They will receive the value from the outter observable (create in this case) and subscribe to the returned inner observable (update in this case) and ouput the value of the inner.

    There are many of them with slightly different use cases / behavior, but switchMap is the most common. When dealing with single emission observables (like http calls), they will all behave identically.

    nested subscribes are generally considered an anti pattern in rxjs and should be avoided as they make it difficult or confusing to properly manage your subscriptions, which is important as you get deeper into rxjs. There are no use cases that exist that would require a nested subscribe or cannot be handled by higher order operators.