[英]How to merge the emitted values of multiple Observables into a single Observable emission?
I have a function that receives a DTO object and transforms it into an observable that emits the single transformed Entity.我有一个 function 接收 DTO object 并将其转换为发出单个转换实体的可观察对象。 It has the following header:它具有以下 header:
dtoTransformer(dto: DTO): Observable<Entity>
I also have a function that returns an Observable emitting a list of DTOs:我还有一个 function ,它返回一个 Observable 发出 DTO 列表:
getDTOs(): Observable<DTO[]>
Using these two I need to write a function that returns an observable of the Entity
list, transformed from the DTOs received:使用这两个我需要编写一个 function ,它返回一个可观察的Entity
列表,从收到的 DTO 转换而来:
getEntyties():Observable<Entity[]>
My problem is applying the dtoTransformer
to the values of the DTO list inside the observable.我的问题是将dtoTransformer
应用于可观察对象内的 DTO 列表的值。 Is there an operator that can help me?有可以帮助我的操作员吗? I don't know how to approach this.我不知道如何处理这个问题。
You can use a combination of forkJoin
and concatMap
.您可以结合使用forkJoin
和concatMap
。 This is under the assumption that these are simple httpClient
(completing) calls:这是假设这些是简单的httpClient
(完成)调用:
getEntities(): Observable<Entity[]> {
return this.getDtos().pipe(
concatMap((dtos) => forkJoin(
dtos.map((dto) => this.dtoTransformer(dto))
)
)
}
What happens here:这里会发生什么:
DTO[]
调用 http 获取DTO[]
map
Map 此响应对 http 调用的数组,使用map
forkJoin
which will do parallel calls and returns when all are completed (and not errored)将这个 observables 数组传递给forkJoin
,它将进行并行调用,并在所有操作完成时返回(并且没有出错) Obviously there are things that you need to take into account, when one http call errors, it doesn't return anything, so you need to add some fallback.显然有些事情需要考虑,当一个 http 调用错误时,它不会返回任何内容,因此您需要添加一些后备。 If the DTO[]
array is very big, you can hit a request limit, so perhaps some throttling can be put in place, or chunking by making a fixed amount in parallel and when those are done continue with the next batch如果DTO[]
数组非常大,您可能会达到请求限制,因此也许可以进行一些限制,或者通过并行制作固定数量的分块,当这些完成后继续下一批
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.