第二个 RxJS `scan' 运算符不是从前一个继续的吗?

The second RxJS `scan' operator does not continues from the previous one?

我有以下 RxJS 代码:code example /* The result is: 4 9 15 4 9 15 */ ...为什么第二个 scan 从头开始​​ (4,9,15) 而不是从前一个 scan 继续(显示 19,24,30)。到底是同一个流?

observables 不是那样工作的。您必须将它们视为水流,您可以在其中与操作员一起换水。每次你用 numbers$ 做某事时,你都会开始新的水流。所以第一个管道与另一个管道无关,反之亦然。

如果您想获得关于第一次扫描的 return 值,您必须保存管道的 return 值并用额外的管道扩展它。

// 'scan' test
let numbers$ = from([4, 5, 6]);

let val1 = numbers$
  .pipe(
    // Get the sum of the numbers coming in.
    scan((total, n) => {
      return total + n
    }),

    // Get the average by dividing the sum by the total number
    // received so var (which is 1 more than the zero-based index).
    //map((sum, index) => sum / (index + 1))
  )

val1.subscribe(x => console.log('value of the first scan is', x))
val1.pipe(
  scan((total, n) => {
    return total + n
  })
).subscribe(console.log);

或者您可以将另一个扫描添加到管道中。但是你会失去第一次扫描的价值:

let numbers$ = from([4, 5, 6]);

numbers$
  .pipe(
    // Get the sum of the numbers coming in.
    scan((total, n) => {
      return total + n
    }),
    scan((total, n) => {
    return total + n
  })
    // Get the average by dividing the sum by the total number
    // received so var (which is 1 more than the zero-based index).
    //map((sum, index) => sum / (index + 1))
).subscribe(x => console.log('value of the second scan is', x))