我有以下 RxJS 代碼:代碼示例
/* The result is: 4 9 15 4 9 15 */
...為什么第二個scan從頭開始 (4,9,15) 而不是從前一個繼續scan(顯示 19,24,30)。畢竟是同一個流嗎?
uj5u.com熱心網友回復:
observables 不是那樣作業的。您必須將它們視為水流,您可以在其中與操作員一起換水。每次你用 numbers$ 做某事時,你都在開始新的水流。所以第一個管道與另一個管道無關,反之亦然。
如果您想獲得關于第一次掃描的回傳值,您必須保存管道的回傳值并用額外的管道擴展它。
// '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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453255.html
標籤:javascript rxjs
