Home > Mobile >  RxJs Operator simplification : switchMap, combineLatest
RxJs Operator simplification : switchMap, combineLatest

Time:12-31

I have the following RxJS subscription :

combineLatest([obs1$, obs2$])
  .pipe(
     filter(val=>!!val[0] && !!val[1]), // no null value on both
     switchMap(([val1, val2]) => combineLatest([of(v1), getObs3$(v2)]))
   )
   .subscribe(([val1, val3]) => { ... });

The code works like intended but it feels cumbersome. I am quite sure the switchMap into combineLatest with an of() opertor is improvable.

Note : In order to call the getObs3$(v2) I need to be sure that the value in obs1$ first. Also, i do need the val1 in the subscription since i will use it later on.

Any one got an idea on how to optimize this one ?

CodePudding user response:

One possibility:

combineLatest([obs1$, obs2$]).pipe(

  // no null value on both
  filter(val=>!!val[0] && !!val[1]),

  switchMap(([val1, val2]) => getObs3$(val2).pipe(
    map(val3 => [val1,val3])
  ))

).subscribe(([val1, val3]) => { ... });

This is the general pattern you'll see quite often for this. Here we insert val3 into a tuple, so it's not much different from combine latest, but if it was enriching an object (however deeply nested) the same pattern would apply.

  • Related