简体   繁体   English

RXJS forkJoin也需要Observable <[]>吗?

[英]RXJS forkJoin also takes Observable<[]>?

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 . 这就像promise.all所以我用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. 但是,重新阅读文档后,此^应该不会起作用。

在此处输入图片说明

Notice that d is type Observable <{}[]> so it's an Observable of array. 请注意, d是类型Observable <{}[]>因此它是数组的Observable。

However the docs says : 但是文档说

sources :SubscribableOrPromise Any number of Observables provided either as an array or as an arguments passed directly to the operator . 来源:SubscribableOrPromise任意数量的Observable ,它们以数组或参数形式直接传递给运算符

But here I don't pass an array. 但是这里我没有传递数组。 ( meaning , this : forkJoin(...d) won't work). (意思是,这: forkJoin(...d)将不起作用)。

Question: 题:

Am I using the forkJoin incorrectly ? 我是否错误地使用了forkJoin? and how is it settled with the docs ? 以及如何与文档一起解决?

OnlineDemo 在线演示

Well, "seems" like it works thanks to mergeMap and toArray but if you look at the output it's probably not what you wanted. 好吧,归功于mergeMaptoArray ,“似乎”可以正常工作,但是如果您查看输出,则可能不是您想要的。 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: 这是您现在得到的:

在此处输入图片说明

[
  [ "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). 这里发生的事情是,您使用mergeMap将每个数字mergeMap到Promise中,然后使用toArray收集所有结果,并且仅在链完成后才发出(将结果数组作为单个发射发射)。 Then forkJoin in fact doesn't subscribe to each individual Promise but only to the resulting Observable after toArray which is fine. 然后, forkJoin实际上并不订阅每个Promise,而是仅订阅toArray之后的结果Observable,这很好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM