Home > Blockchain >  Mapping after concatmap
Mapping after concatmap

Time:10-21

I have the following observable:

existingFormData$: Observable<any> = this.activatedRoute.params.pipe(
    map(params => params['id']),
    filter(id => !!id),
    switchMap((id: string) => this.httpService.getUniversityApplicationsDetail(id)),
    concatMap((detail: any) => this.httpService.getUniversityApplicationsFeesOptions(detail.meta.university.id)),
    tap((detail: any) => {
      console.log(detail)
    })
  );

I'm looking up the id contained in the address bar, calling up the 1st api, getting an id value from the 1st api and sending that off to the 2nd api. Both apis return an object. Is concatMap the correct operator for this? It seems to work looking in my Network tab.

The problem I have is that both apis have exactly the same structure. How can I construct 1 object which looks like this:

{
    apiOne: apiOne,
    apiTwo: apiTwo
}

CodePudding user response:

You can combine the results from both calls by adding another pipe after your second call. This allows both of your response variables to be in the same scope, so you can form an object from the two values.

This technique is explained in more detail here.

existingFormData$: Observable<any> = this.activatedRoute.params.pipe(
    map(params => params['id']),
    filter(id => !!id),
    switchMap(id => this.httpService.getUniversityApplicationsDetail(id)),
    switchMap(detail => this.httpService.getUniversityApplicationsFeesOptions(detail.meta.university.id).pipe(
        map(options => ({ detail, options }))
    )),
    tap(obj => {
      console.log(obj)
    })
  );

Note: if your service methods only emit a single value, it doesn't matter if you use concatMap or switchMap, the behavior will be the same. The difference comes into play when an observable emits multiple values.

  • concatMap will wait for the first inner source to complete before subscribing to the next
  • switchMap will unsubscribe from the current inner source as soon as a new emission is received (it doesn't wait for completion)
  • Related