RxJS/Observable flatMap 可以 return Observable 或 array

RxJS/Observable flatMap can return Observable or array

有人可以向我解释为什么 .flatMap 运算符可以接受 return 是 Observablearray 的函数吗?

official docs 说:

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.

为什么它也可以return一个数组

例如,这两个都有效:

obs$.flatMap((data) => {
    return [];
});

obs$.flatMap((data) => {
    return new Observable<string>();
});

但这不起作用:

obs$.flatMap((data) => {
    return 1;
});

官方文档不相关,因为它们指的是 RxJS 4 而不是 RxJS 5。

mergeMap投影函数returnsnot 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.

这意味着

obs$.flatMap((data) => arr)

基本上是

的一个较短版本
obs$.flatMap((data) => Observable.from(arr))