RxJS implements the basic flatMap
operator. It has a variant that allows you to
apply a transformative function (an optional second parameter to flatMap
) to the
items emitted by the Observables generated for each item in the source Observable, before
merging and emitting those items.
flatMap
works just as well if the function you provide transforms items from the
source Observables into Observables, into Promises, or into arrays.
“selectMany
” is an alias for flatMap
.
Sample Code
var source = Rx.Observable
.range(1, 2)
.selectMany(function (x) {
return Rx.Observable.range(x, 2);
});
var subscription = source.subscribe(
function (x) { console.log('Next: ' + x); },
function (err) { console.log('Error: ' + err); },
function () { console.log('Completed'); });
Next: 1
Next: 2
Next: 2
Next: 3
Completed
// Using a promise
var source = Rx.Observable.of(1,2,3,4)
.selectMany(function (x, i) {
return Promise.resolve(x + i);
});
var subscription = source.subscribe(
function (x) { console.log('Next: ' + x); },
function (err) { console.log('Error: ' + err); },
function () { console.log('Completed'); });
Next: 1
Next: 3
Next: 5
Next: 7
Completed
// Using an array
Rx.Observable.of(1,2,3)
.flatMap(
function (x, i) { return [x,i]; },
function (x, y, ix, iy) { return x + y + ix + iy; }
);
var subscription = source.subscribe(
function (x) { console.log('Next: ' + x); },
function (err) { console.log('Error: ' + err); },
function () { console.log('Completed'); });
Next: 2
Next: 2
Next: 5
Next: 5
Next: 8
Next: 8
Completed
flatMap
is found in each of the following distributions:
rx.js
rx.all.js
rx.all.compat.js
rx.compat.js
rx.lite.js
rx.lite.compat.js