简体   繁体   English

组合多个请求并按顺序订阅 rxjs

[英]Combine multiple requests and subscribe sequentially with rxjs

I have a loop that sends x http requests.我有一个发送 x http 请求的循环。

In some cases user can send a so many requests and that could affect server performances.在某些情况下,用户可以发送如此多的请求,这可能会影响服务器性能。

I would like to convert existing logic and be able ho manage max requests number.我想转换现有逻辑并能够管理最大请求数。

Sample code示例代码

for( let i; i<x; i++ ) {
  this.subs= this.globalService.getData(formData, id).subscribe(data => {...}
}

How can I authorise triger only if the number of requests is < 10 for example otherwise wait for api response and check if current observers is less than 10?例如,仅当请求数 < 10 时,我如何才能授权触发,否则等待 api 响应并检查当前观察者是否小于 10?

It's important to subscribe sequentially and not send an array of data to not change code logic inside subscription.重要的是按顺序订阅并且不发送数据数组以不更改订阅内的代码逻辑。

Probably the easiest way is using mergeMap() with an optional concurrency option.可能最简单的方法是使用带有可选concurrency选项的mergeMap()

range(x)
  .pipe(
    mergeMap(i =>  this.globalService.getData(formData, i), 10),
  )
  .subscribe();

This way you can make mergeMap() to perform at most 10 concurrent requests.这样您就可以使mergeMap()执行最多 10 个并发请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM