简体   繁体   English

RXJS如何将Observable <T []>转换为Observable <T>

[英]RXJS How to convert Observable<T[]> to Observable<T>

I would like to take an Observable<T[]> and convert it to an Observable<T> such that each array from the Observable<T[]> is broken up and the individual elements of the arrays are then emitted, separately, via the Observable<T>. 我想采用Observable <T []>并将其转换为Observable <T>,以便Observable <T []>中的每个数组都被分解,然后通过单独的方式发出数组的各个元素Observable <T>。

Is there a standard operator for doing this? 这样做有标准的操作员吗? I've searched around but haven't found anything. 我已经四处寻找但没找到任何东西。 Thanks. 谢谢。


After being pointed in the direction of concatMap/flatMap, I came up with the following general solution: 在指向concatMap / flatMap的方向后,我提出了以下一般解决方案:

var source: Observable<T[]>;
...
var splitSource = source.flatMap<T>((x:T[]) => { return Rx.Observable.fromArray(x); });

You could use concatMap like this: 您可以像这样使用concatMap

function identity (x) {return x}

var obs_of_array$ = Rx.Observable.return(['1','2','you got it'])
    .concatMap(identity)

This works because concatMap also accepts arrays (and observables and promises) as the return value of the function selector that you pass as a parameter. 这是有效的,因为concatMap还接受数组(和observables和promises)作为您作为参数传递的函数选择器的返回值。 Jsbin here , documentation here Jsbin 在这里 ,文档在这里

So the array passed as parameter becomes the return value from the selector function, and then is flattened by the concatMap operator while respecting the ordering of the array. 因此,作为参数传递的数组成为选择器函数的返回值,然后由concatMap运算符展平,同时concatMap数组的顺序。

I've also been playing around with converting Observable<T[]> to Observable<T> . 我也一直在努力将Observable<T[]>转换为Observable<T>

I've found that flatMap() does the job on it's own, which I presume was not the case 11 months ago when the question was asked. 我发现flatMap()完成了它自己的工作,我认为11个月前问题的问题并非如此。

To illustrate, in the jsfiddle in @user3743222's answer, you can make this change and get the same output: 为了说明,在@ user3743222的答案的jsfiddle中,您可以进行此更改并获得相同的输出:

//.concatMap(identity)
.flatMap(theArray=>theArray)

I use this and the toArray() operator to perform set operations in the pipeline, for example to sort the observable. 我使用this和toArray()运算符在管道中执行set操作,例如对observable进行排序。

    let sorted$ = source$.toArray().flatMap(theList=> theList.sort(this.myComparer) )

The output is Observable<T> . 输出是Observable<T> ( NB works in the context of a fixed array, not sure what would happen with a continuously generating source) NB在固定数组的上下文中工作,不确定连续生成源会发生什么)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM