[英]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
? 有人可以向我解释为什么
.flatMap
运算符可以接受一个返回Observable
或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.
FlatMap运算符通过将您指定的函数应用于源Observable发出的每个项来转换Observable, 其中该函数返回一个本身发出项的Observable。
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;
});
The official docs are not relevant because they refer to RxJS 4 and not RxJS 5. 官方文档不相关,因为它们指的是RxJS 4而不是RxJS 5。
mergeMap
projection function returns not just Observable
but ObservableInput
interface , which applies to miscellaneous values that can be converted to observables : mergeMap
投影函数不仅返回Observable
而且还返回ObservableInput
接口 ,该接口适用于可以转换为observables的其他值 :
Arrays can be interpreted as observables that emit all values in array one by one, from left to right, and then complete immediately.
数组可以解释为observable,从左到右逐个发出数组中的所有值,然后立即完成。
This means that 这意味着
obs$.flatMap((data) => arr)
is basically a shorter version of 基本上是一个较短的版本
obs$.flatMap((data) => Observable.from(arr))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.