0

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 ?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.