RXJS forkJoin also takes Observable<[]>?

Royi Namir

I have an array of numbers which I transform each number to an observable (which emits at random time)

When all observable are resolved , I display the result.

It's like promise.all so I'm using forkJoin.

let arr: Array<Number> = [1, 2, 3, 4, 5];
let d = from(arr).pipe(mergeMap(f => myPromise(f)), toArray());
const example = forkJoin(d);
const subscribe = example.subscribe(val => console.log(val));

This does work as expected and I do see the overall results after random (max) time.

However , re-reading the docs , this ^ should not have worked.

enter image description here

Notice that d is type Observable <{}[]> so it's an Observable of array.

However the docs says :

sources :SubscribableOrPromise Any number of Observables provided either as an array or as an arguments passed directly to the operator.

But here I don't pass an array. ( meaning , this : forkJoin(...d) won't work).

Question:

Am I using the forkJoin incorrectly ? and how is it settled with the docs ?

OnlineDemo

martin

Well, "seems" like it works thanks to mergeMap and toArray but if you look at the output it's probably not what you wanted. It emits the resulting array inside another array while it looks like you wanted to get just an array of results.

This is what you get right now:

enter image description here

[
  [ "Promise Resolved: 1", "Promise Resolved: 2", "Promise Resolved: 3", "Promise Resolved: 4", "Promise Resolved: 5" ],
]

What's going on here is that you used mergeMap to project each number into a Promise and then toArray to collect all results and only after that the chain completes (it emits the resulting array as a single emission). Then forkJoin in fact doesn't subscribe to each individual Promise but only to the resulting Observable after toArray which is fine.

The documentation is correct because it allows multiple use cases such as:

forkJoin(a, b, c); // Observables as arguments passed directly to the operator

or

forkJoin([a, b, c]); // Observables as an array

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related