RxJS / Observable flatmap can return Observable or array
Can someone explain to me why an operator .flatMap
can accept a function that returns Observable
or array
?
the official docs say:
The FlatMap operator transforms an Observable by applying a function that you tell each item emitted by an Observable source , where this function returns an Observable that emits items itself.
Why can it also return an array ?
For example, they are both valid:
obs$.flatMap((data) => {
return [];
});
obs$.flatMap((data) => {
return new Observable<string>();
});
But this doesn't work:
obs$.flatMap((data) => {
return 1;
});
The official docs are not up to date as they refer to RxJS 4 and not RxJS 5.
mergeMap
The projection function returns not only Observable
, but an ObservableInput
interface that is applied to different values โโthat can be converted to observable files :
Arrays can be interpreted as observables that emit all the values โโin the array one by one, from left to right, and then terminate immediately.
It means that
obs$.flatMap((data) => arr)
is basically a shorter version
obs$.flatMap((data) => Observable.from(arr))