Reputation: 1647
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;
});
Upvotes: 9
Views: 4673
Reputation: 223194
The official docs are not relevant because they refer to RxJS 4 and not RxJS 5.
mergeMap
projection function returns not just Observable
but ObservableInput
interface, which applies to miscellaneous values that can be converted to observables:
Arrays can be interpreted as observables that emit all values in array one by one, from left to right, and then complete immediately.
This means that
obs$.flatMap((data) => arr)
is basically a shorter version of
obs$.flatMap((data) => Observable.from(arr))
Upvotes: 7