switchMap inside pipe() VS sequence of switchMap

Viewed 884

I didn't get if there is a difference between this:

Observable.pipe( 
           switchMap((res) => {
             ...
            }),
            switchMap((res) => {
             ...
            })
);

and this:

Observable.pipe(
            switchMap((res) => {
             ...
            }).pipe(
                 switchMap((res) => {
                 ...
                 }),
            )
  );      

Can you help me understanding if there is differences in the way data are treated?

Thank you

2 Answers

As it is written, there is no difference, however if you later want to add further items down the pipe, it might matter. For example catchError - In the first case, if you add it at the end of the pipe, then it will catch errors thrown by either step of the pipe, but in the 2nd example, you can put it inside the first pipe, after the inner switchMap and it will only catch errors on the inner operation.

Oh I just read @serrulien's comment, and he's right, your 2nd pipe cannot be placed where you placed it, it would have been placed inside the body of the first switchMap, e.g.:

Observable.pipe(
  switchMap((res) => {
    return someObservable().pipe(
      switchMap((res) => {
        ...
      })
  })
);     

As the saying goes, there are many ways to skin a cat.

RxJS#pipe is just function composition flipped. It turns out that (like addition), composition is associative.


For addition:
x + (y + z) = (x + y) + z

For composition:
x ∘ (y ∘ z) = (x ∘ y) ∘ z


What does this mean? Well, you can sort of think of the pipe function as the parentheses in a math equation.

These are all the same expression, just with parentheses in different places: (and since piped RxJS operators are associative, it doesn't matter where the parentheses are)

// 1
stream.pipe(
  switchMap(/*...*/),
  concatMap(/*...*/),
  delay(/*...*/),
  toArray()
);

// 2
stream.pipe(
  switchMap(/*...*/),
  concatMap(/*...*/)
).pipe(
  delay(/*...*/),
  toArray()
);

// 3
stream.pipe(
  switchMap(/*...*/)
).pipe(
  concatMap(/*...*/)
).pipe(
  delay(/*...*/)
).pipe(
  toArray()
);
Related