Why switchMap(forkJoin) fails but switchMap(arr=>forkJoin(arr)) works fine?

Viewed 82

I have following code

const mySource:Observable<Observable<any>[]>

(...)

mySource.pipe(
   switchMap(arr=>forkJoin(arr));
)

which works as expected, but

mySource.pipe(
   switchMap(forkJoin);
)

fails with

REST error TypeError: You provided '0' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
    RxJS 31
        subscribeTo
        from
        forkJoinInternal
        _trySubscribe
        subscribe
        innerSubscribe
        _innerSub

Why is the second variant not working?

Stackblitz: https://stackblitz.com/edit/typescript-tztgpl?file=index.ts

Keep in mind that this is a runtime error, not an IDE related stuff.

1 Answers

The two calls are actually not equivalent. switchMap passes to its projection function two arguments. The value from source and an internal index. You can see it here: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/switchMap.ts#L106

So using the following:

switchMap(forkJoin),

is in fact equivalent to using:

switchMap((value, index) => forkJoin(value, index)),

... and this obviously throws an error because 0 is not an Observable. Btw, this would stop working in future versions of RxJS anyway because forkJoin thinks you're listing source Observales (forkJoin([obs1, obs2], obs3)) which is deprecated and it wouldn't subscribe to individual Observables in that array. In other words, it wouldn't flatten the chain.

You can check this small demo: https://stackblitz.com/edit/rxjs-mgb3fx?devtoolsheight=60

Related