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;
});
Summary. We've seen that operators like map and filter are functions which take in and return observables. Each operator exposes a public function like map or filter , which is what we import from 'rxjs/operators' and pass into pipe .
Returns Observable Returns an Observable that emits a boolean based on the input value: If no predicate method, the value will be converted to it's Boolean value.
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. FlatMap then merges the emissions of these resulting Observables, emitting these merged results as its own sequence.
If multiple requests come in at once then they will all make a request to get the token. To avoid that I share an observable so that the result for getting the token is shared and that only one request is made to get the token. The problem is that flatMap is deprecated and replacing it with mergeMap won't work either.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With