Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS/Observable flatMap can return Observable or array

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;
});
like image 940
Dolan Avatar asked Jul 22 '17 23:07

Dolan


People also ask

Does RxJS map return Observable?

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 .

What is the return type of Observable?

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.

What is Observable flatMap?

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.

Is flatMap deprecated in RxJS?

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.


1 Answers

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))
like image 75
Estus Flask Avatar answered Nov 01 '22 04:11

Estus Flask