无需等待所有完成的并行 rxJs Observables [英] Parallel rxJs Observables without waiting for all to complete

查看:34
本文介绍了无需等待所有完成的并行 rxJs Observables的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使用 rxJs Observables 并行请求许多类似的请求, 无需等待所有请求完成.我想处理每一个来.我不想使用请求循环.用例之一是请求很慢并且有很多我尝试了 forkJoin(如下),但它等待所有完成.并且 mergeMap 没有采用数组.有什么帮助吗?谢谢

Is there a way to request many similar requests in parallel using rxJs Observables in parallel without waiting for all requests to complete. I want to handle as each one comes. I don't want to use a loop of requests. Use case is one of the request is slow and there are many of them I tried forkJoin (below) but it waits for all to complete. and mergeMap is not taking an array. Any help? Thanks

/*
  // example of many posts
  const post1 = getPostHTTP(1);
  const post2 = getPostHTTP(2); // A slow post
  const post3 = getPostHTTP(3);
  ...
*/

const promises = [];

for (let i = 0; i < 100; i++) {
    promises.push(getPostHTTP(i))
}

forkJoin(promises).pipe(
    finalize(() => {
        //displayPost
    })).subscribe(posts => {
        posts.forEach((post: any) => {
            displayPost(post)
        })
    })

推荐答案

我认为 frommergeMap 的组合是您正在寻找的.代码看起来像这样

I think that a mix of from and mergeMap is what you are looking for. The code could look like this

for (let i = 0; i < 100; i++) {
    promises.push(getPostHTTP(i))
}

from(promises).pipe(
  mergeMap(post => displayPost(post)),
).subscribe(
  next: result => {// do something with the result of each displayPost operation},
  error: err => {// handle errors},
  complete: () => {// do something when everything is completed}
)

这篇关于无需等待所有完成的并行 rxJs Observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆