AlanObject
AlanObject

Reputation: 9983

Convert a method with nested subscribes to an RxJS pipe

I have a code pattern that looks (simplified) like this:

loadDocs(): DocType {
    this.http.get('/doc/1').subscribe(
      (doc1) => {
        this.http.get('/doc/' + '(something based on doc1)').subscribe(
          (doc2) => {
              return doc2;
          }
        );
      }
    );
  }

What I want to do is convert that to a function that returns an Observable like:

loadDocs(): Observable<TypeDoc> {
    return this.http.get('/doc/1').pipe(
       // ???
    );
}

I am sure this is very basic but so far I haven't been able to find an example of which RxJS operators to use in this case.

Upvotes: 0

Views: 201

Answers (1)

bryan60
bryan60

Reputation: 29355

you're looking for switchMap in this case:

loadDocs(): Observable<TypeDoc> {
    return this.http.get('/doc/1').pipe(
       switchMap(doc1 => this.http.get('/doc/' + '(something based on doc1)'))
    );
}

mergeMap and concatMap would work the same here since http calls are single emission observables, the differences between them are only apparent with observables that emit multiple times. IMO switchMap is semantically most correct with http calls as it implies there will only be one active inner subscription, but opinions on this will vary.

They're all higher order operators that take the current value and map it into a new inner observable that they subscribe to and return the value

Upvotes: 3

Related Questions