如何从 Observable.from 收集发出的值数组? [英] How to collect array of emitted values from Observable.from?

查看:33
本文介绍了如何从 Observable.from 收集发出的值数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在 Rxjs 中,我有一堆代码,

So in Rxjs, I have bunch of code,

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里面的code,所以我想知道如何在observablefrom操作符中收集每个item的输出数组?

But apparently this is wrong, the scan will break the code inside the concatMap, so I want to know how to collect the output array of each item in the observable from operator?

推荐答案

在您对 scan 的调用中 您没有为累加器指定种子.在这种情况下,第一个值用作种子.例如:

In your call to scan you have not specified a seed for the accumulator. In that circumstance, the first value is used as a seed. For example:

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.要将值累积到数组中,您可以指定一个数组种子,如下所示:

In your snippet, the first value is not an array, so you cannot call push on it. To accumulate the values into an array, you can specify an array seed like this:

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>

虽然,对于某些用例,最好不要改变数组:

Although, for some use cases, it would be preferable to not mutate the array:

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 会为其接收到的每个值发出一个数组.如果您只想在 observable 完成时发出单个数组,则可以改用 toArray 运算符:

Note that scan emits an array for each value that it receives. If you only want a single array emitted when the observable completes, you can use the toArray operator instead:

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>

这篇关于如何从 Observable.from 收集发出的值数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆