还是不明白 RXJS operator combineLatestAll 是如何工作的?

Still don't understand how RXJS operator combineLatestAll works?

我编写了以下示例,但仍然无法理解输出!

import { combineLatestAll, of, map } from 'rxjs';

const s1 = of(1, 2, 3).pipe(
  map(v1 =>
    of(100, 101, 102, 103, 104).pipe(
      map(v2 => [v1,v2])
    )
  ),
  combineLatestAll()
);

s1.subscribe(console.log);

输出为:

[ [ 1, 104 ], [ 2, 104 ], [ 3, 100 ] ]
[ [ 1, 104 ], [ 2, 104 ], [ 3, 101 ] ]
[ [ 1, 104 ], [ 2, 104 ], [ 3, 102 ] ]
[ [ 1, 104 ], [ 2, 104 ], [ 3, 103 ] ]
[ [ 1, 104 ], [ 2, 104 ], [ 3, 104 ] ]

我看了很长时间的输出,但仍然无法理解这个运算符的行为。

在你理解combineLatestAll之前,让我们分析一下combineLatest的行为。

根据显示的弹珠图 here,如果我们有 2 个数据流,那么 combineLatest 会“合并”这两个数据流的最新值。

意思是,在它订阅的 2 个流中,除非它们都开始发出数据,否则您将看不到任何输出。

但是,如果第一个流在第二个流开始时已经完成,会发生什么情况。

var c1 = of(5, 15, 25);
var c2 = of(6, 16, 26);

var s2 = combineLatest([c1,c2]);
s2.subscribe(console.log) // Outputs = [25,6] [25,16] and [25, 26]

在这种情况下,combineLatest 运算符将从 source1 中获取 latest/last 值(上例中为 25),然后在第二个流开始时开始发出输出(结合 latest/last 来自 source1 的值和来自 source2 的所有传入值)

如果有 3 个来源呢? 在这种情况下,combineLatest 仅当所有 3 个流都已开始生成输出时才会生成输出。

var c1 = of(5, 15, 25);
var c2 = of(6, 16, 26);
var c3 = of(7, 17, 27);

var s2 = combineLatest([c1,c2, c3]);
s2.subscribe(console.log) // Outputs = [25,26, 7] [25,26, 17] and [25, 26, 27]

在上面的例子中,当第三个 observable 开始发射值时,其他 2 个 observable 已经完成。因此,输出类似于从前两个来源获取 latest/last 值,然后将其与第三个可观察值的所有值组合。

上面的例子也可以写成-

var s3 = of(c1, c2, c3).pipe(combineLatestAll());
s3.subscribe(console.log);

在您原来的问题中,您看到了完全相同的行为。前 2 个 observable 具有最新值,然后它与最后一个 observable 的每个值组合。