转换rjxs映射并将flatten/reduce转换为flatMap [英] convert rjxs map and flatten/reduce to flatMap
问题描述
我相信以下代码可以使用flatMap进行重构,但是我似乎无法使其按需工作.
I believe the following code can be refactored using a flatMap but I cant seem to get it working as desired.
我了解flatMap本质上是映射然后进行展平,这对我来说是完美的,因为我正在使用forkJoin,因此可以从getAutocompleteSuggestions()返回一系列响应.
I understand flatMap essentially maps and then flattens, which is perfect for me as I'm using forkJoin so get an array of responses back from getAutocompleteSuggestions().
我希望在订阅时获得一个结果数组(这是下面的代码生成的结果),但是将顶级映射更改为flatMap会将多个单个对象发送给订阅.如何用flatMap()更好地编写此代码?
I want a single array of results upon subscription (which is what the code below produces), but changing the top level map to flatMap sends multiple single objects to the subscription. How can this code be better written with flatMap()?
const $resultsObservable: Observable<any> = Observable.of(query)
.switchMap(q => this.getAutocompleteSuggestions(q))
//tried changing the below to flatMap()
.map(res => {
return res.map(resp => {
const content = resp.content;
content.map(result => this.someMethod(result));
return content;
})
.reduce((flatArr, subArray) => flatArr.concat(subArray), []);
});
getAutocompleteSuggestions(query: string): Observable<any> {
const subs$ = [];
//... add some observables to $subs
return Observable.forkJoin(...subs$);
}
推荐答案
RxJS flatMap
与Array原型方法 flatMap
.请注意,RxJS flatMap的目的不是将流的主题数组展平,而是将Obervable的流展平为单个可观察的对象.看到这样的帖子:
It looks like there might be a bit of confusion between the RxJS flatMap
and the Array prototype method flatMap
. Note that the purpose of the RxJS flatMap is not to flatten arrays that are the subjects of the stream, but rather to flatten a stream of Obervables into a single observables. See this SO post:
...基本上,如果Observable表示一个可推对象,该对象推入类型T的值,则flatMap将类型T'-> Observable的函数作为其参数,并返回Observable.map使用类型为T'-> T的函数并返回Observable.
... Basically if Observable denotes an observable object which pushes values of type T, then flatMap takes a function of type T' -> Observable as its argument, and returns Observable. map takes a function of type T' -> T and returns Observable.
如果希望代码更简洁一点,可以使用 myArray.flatMap
方法.这是使用Array flatMap
方法对您的问题的可能答案:
If you want your code to be a bit cleaner, you could use the myArray.flatMap
method. Here's a potential answer to your question with the Array flatMap
method:
const $resultsObservable: Observable<any> = Observable.of(query)
.switchMap(q => this.getAutocompleteSuggestions(q))
// Flatmap on the array here because response is an array of arrays.
// The RxJS flatMap does not deal with flattening arrays
.map(res => res.flatMap(resp => {
const content = resp.content;
content.map(result => this.someMethod(result));
return content;
}));
getAutocompleteSuggestions(query: string): Observable < any > {
const subs$ = [];
//... add some observables to $subs
return Observable.forkJoin(...subs$);
}
这篇关于转换rjxs映射并将flatten/reduce转换为flatMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!