Can someone explain to me why the .flatMap
operator can accept a function which returns an Observable
, or an array
?
The official docs say:
The FlatMap operator transforms an Observable by applying a function that you specify to each item emitted by the source Observable, where that function returns an Observable that itself emits items.
Why can it also return an array?
For example, these are both valid:
obs$.flatMap((data) => {
return [];
});
obs$.flatMap((data) => {
return new Observable<string>();
});
But this does not work:
obs$.flatMap((data) => {
return 1;
});
1
is neither an array nor an observable, so of course it doesn't work. – AlikaflatMap
is an alias formergeMap
. Check the docs and you will see the function can return an observable, a promise, or an array-like value: reactivex.io/rxjs/class/es6/… – AlikaObservableInput
: reactivex.io/rxjs/class/es6/… – AlikaObservableInput
. So how can.flatMap
return an array of Observables? Or is that not possible? – GautflatMap
on an array of observables, you'll get an observable of observables - termed a higher-order observable. There are operators to further flatten such higher-order observables. Look atmergeAll
andconcatAll
. Also, if the links have helped you understand things, you might want to consider adding a self answer. – Alika