gpt4 book ai didi

javascript - 转换 rjxs map 并展平/缩减为 flatMap

转载 作者:行者123 更新时间:2023-12-03 02:20:13 24 4
gpt4 key购买 nike

我相信可以使用 flatMap 重构以下代码,但我似乎无法让它按预期工作。

我理解 flatMap 本质上是映射然后展平,这对我来说是完美的,因为我正在使用 forkJoin,因此可以从 getAutocompleteSuggestions() 返回一组响应。

我想要订阅时的单个结果数组(这是下面的代码生成的结果),但是将顶级映射更改为 flatMap 会向订阅发送多个单个对象。如何使用 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 和数组原型(prototype)方法 flatMap 之间可能存在一些混淆。请注意,RxJS flatMap 的目的不是展平作为流主题的数组,而是将 Obervables 流展平为单个 observables。请参阅此帖子:

Why do we need to use flatMap?

... 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 方法对您的问题的潜在答案:

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$);
}

关于javascript - 转换 rjxs map 并展平/缩减为 flatMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49191962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com