你靠近,我觉得你只需要几个运营商的分组观察到的阵列。
const list = [{ type: 'foo' }, { type: 'bar' }, { type: 'bar' }];
Observable.from(list).groupBy(x => x.type)
.mergeMap(list$ => { // each emission is a stream
/* A stream of "aggregated" data. */
const count$ = list$.count();
/* Format the result. */
return count$.map(count => ({ type: list$.key, count }));
});
这发出:
{ type: 'foo', total: 1 }
{ type: 'bar', total: 2 }
这听起来像你可能有计算“集合”更复杂的使用案例,也许你需要总结Sample.data
。如果是这样,你只需要改变我自己的count$
实施。比方说,data
是号码清单:
const list = [{
type: 'foo',
data: [1,2,3]
}, {
type: 'bar',
data: [4,5,6]
}, {
type: 'bar',
data: [7,8,9]
}];
Observable.from(list).groupBy(x => x.type)
.mergeMap(list$ => { // each emission is a stream
/* A stream of "aggregated" data. */
const count$ = list$.reduce((accumulator, sample) => { // reduce the stream
return accumulator + sample.data.reduce((acc, datum) => { // reduce the array
return acc + datum;
}, 0);
}, 0);
/* Format the result. */
return count$.map(count => ({ type: list$.key, count }));
});
这将产生:
{ type: 'foo', total: 6 }
{ type: 'bar', total: 39 }
您可以简化这一点,因为与该分组由该值可通过'key'财产上的[ 'GroupedObservable'](http://reactivex.io/rxjs/class/es6/operator/groupBy.js~GroupedObservable.html)。也就是说,你不需要使用'list $ .take(1).map(x => x.type)'来获得它;只需使用'list $ .key'。 – cartant
非常棒,谢谢。我已经更新了答案。 – xtianjohns