我有很多请求,比如:
let array = [req1,req2,req3.....,req(n)]
目前,我只在收到所有请求响应后才使用forkJoin来呼叫订户。现在,我想修改我的代码以批量进行api调用,但是只有在完成所有批处理响应后才能调用订阅者,这是可能的吗?
示例
public demoCalls() {
let demoForkJoin
var a = [req1,req2,....,req45]
a.map((data,index)=>{
demoFrokJoin[index] = this.http.post()
})
forkJoin(demoForkJoin)
}
现在,我要调用10-10 req,而不是这个批处理。每个10 req将在1000 be后调用。
只有在收到所有api的响应后,才会调用一个订阅者。(所有45个api)
demoCall().subscribe(res=>{
// this subscribe only once after all calls are completed and got success result
})
发布于 2022-07-01 07:35:09
我建议使用一些rxjs操作符的并发值,而不是批处理。例如,mergeMap
提供了这个值。在完成一个可观测的操作之后,下一个可观测到的就被订阅了。为finish操作添加finalize
。
下面的示例有两个并发请求
import { Observable, of, range } from 'rxjs';
import { delay, finalize, mergeMap } from 'rxjs/operators';
function req(id: number): Observable<number> {
console.log('request received for id', id);
return of(id).pipe(delay(5000));
}
range(0, 10)
.pipe(
mergeMap((r) => req(r), 2),
finalize(() => console.log('all requests done'))
)
.subscribe((id) => console.log('request completed for id', id));
在Stackblitz:https://stackblitz.com/edit/typescript-cmylca?file=index.ts上查看此操作
https://stackoverflow.com/questions/72819404
复制相似问题