iam1me iam1me - 1 year ago 101
Javascript Question

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); });

Answer Source

You could use concatMap like this:

function identity (x) {return x}

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download