所以在 Rxjs 中,我有一堆代码,
return Observable.from(input_array)
.concatMap((item)=>{
//this part emits an Observable.of<string> for each item in the input_array
})
.scan((output_array:string[],each_item_output_array:string)=>{
return output_array.push(each_item_output_array) ;
});
但显然这是错误的,扫描会破坏 concatMap 内的代码,所以我想知道如何收集可观察中每个项目的输出数组from
操作员?
在您致电时scan http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-scan您尚未为累加器指定种子。在这种情况下,第一个值被用作种子。例如:
Rx.Observable
.from(["a", "b", "c"])
.scan((acc, value) => acc + value)
.subscribe(value => console.log(value));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
在您的代码片段中,第一个值不是数组,因此您无法调用push
在上面。要将值累积到数组中,您可以指定一个数组种子,如下所示:
Rx.Observable
.from(["a", "b", "c"])
.concatMap(value => Rx.Observable.of(value))
.scan((acc, value) => {
acc.push(value);
return acc;
}, []) // Note that an empty array is use as the seed
.subscribe(value => console.log(JSON.stringify(value)));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
不过,对于某些用例,最好不要改变数组:
Rx.Observable
.from(["a", "b", "c"])
.concatMap(value => Rx.Observable.of(value))
.scan((acc, value) => [...acc, value], [])
.subscribe(value => console.log(JSON.stringify(value)));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
注意scan
为它接收到的每个值发出一个数组。如果您只想在可观察完成时发出单个数组,则可以使用toArray
运算符改为:
Rx.Observable
.from(["a", "b", "c"])
.concatMap(value => Rx.Observable.of(value))
.toArray()
.subscribe(value => console.log(JSON.stringify(value)));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)