Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>.

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:

var source: Observable<T[]>;
...
var splitSource = source.flatMap<T>((x:T[]) => { return Rx.Observable.fromArray(x); });
like image 641
iam1me Avatar asked Mar 15 '16 18:03

iam1me


1 Answers

You could use concatMap like this:

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. Jsbin here, documentation here

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.

like image 149
user3743222 Avatar answered Nov 15 '22 13:11

user3743222