问题描述
代码:
const Rx = require('rxjs')
const data = [
{ name: 'Zachary', age: 21 },
{ name: 'John', age: 20 },
{ name: 'Louise', age: 14 },
{ name: 'Borg', age: 15 }
]
const dataSubj$ = new Rx.Subject()
function getDataStream() {
return dataSubj$.asObservable().startWith(data);
}
getDataStream()
.mergeMap(Rx.Observable.from)
.scan((arr, person) => {
arr.push(person)
return arr
}, [])
.subscribe(val => console.log('val: ', val));
使用 .reduce(...) 而不是 .scan(...) 会返回一个空数组,并且不会打印任何内容.dataSub$ 的观察者应该接收一个数组.
为什么 scan 允许数据元素通过,而 reduce 不允许?
注意:我使用 mergeMap 是因为我会先过滤数组的元素,然后再将它们减少回单个数组.
Using .reduce(...) instead of .scan(...) returns an empty array and nothing is printed. The observer of dataSub$ should receive an array.
Why does scan allow elements of data to pass through, but reduce does not?
Note: I am using mergeMap because I will filter the elements of the array before reducing them back into a single array.
推荐答案
scan 发出每个源项目的累积值.
scan emits the accumulated value on every source item.
reduce 仅发出最后一个累积值.它等待源 Observable 完成,然后才发出累积值.
reduce emits only the last accumulated value. It waits until the source Observable is completed and only then emits the accumulated value.
在您的情况下,依赖于主题的源 Observable 永远不会完成.因此,reduce 永远不会发出任何值.
In your case the source Observable, which relies on a subject, never completes. Thus, the reduce would never emit any value.
您可能希望对 mergeMap 的内部 Observable 应用缩减.对于每个数组,当所有数组项都发出时,内部 Observable 将完成:
You may want to apply the reduce on the inner Observable of the mergeMap. For each array, the inner Observable would complete when all the array items are emitted:
const data = [
{ name: 'Zachary', age: 21 },
{ name: 'John', age: 20 },
{ name: 'Louise', age: 14 },
{ name: 'Borg', age: 15 }
]
const dataSubj$ = new Rx.Subject()
function getDataStream() {
return dataSubj$.asObservable().startWith(data);
}
getDataStream()
.mergeMap(arr => Rx.Observable.from(arr)
.reduce((agg, person) => {
agg.push(person)
return agg
}, [])
)
.subscribe(val => console.log('val: ', val));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.6/Rx.js"></script>
这篇关于Reduce 返回空数组,但 scan 不返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!