首页 > 解决方案 > 使用 RxJS 无限计算并发的 HttpClient 请求

问题描述

我一直试图以一种很好的反应方式计算并发的 HttpClient 请求。在这个示例中,我使用间隔作为请求触发器,但实际上可能是其他一些异步事件。我不想在每次通话之前和之后点击并更新一些全局counter可观察的。httpClient我很确定应该有一些更好的方法。

let a11$ = interval(1000); 
let a12$ = interval(1500);
let a13$ = interval(3000);

let c1$ = combineLatest(a11$, a12$, a13$).pipe(
    map(([a, b ,c]) => {
        return this.httpClient.get(`http://example.com/${a}${b}${c}`);
    })
)

let a21$ = interval(4000); 
let a22$ = interval(4500);
let a23$ = interval(5000);


let c2$ = combineLatest(a21$, a22$, a23$).pipe(
    map(([a, b ,c]) => {
        return this.httpClient.get(`http://example.com/${a}${b}${c}`);
    })
)


let count$ = null; // I want to calculate how many concurrent HTTP requests produced by c1$ and c2$ are being executed at the moment. Infinitely.

标签: angularrxjsreactive-programming

解决方案


有一个count()带有 rxjs 的运算符,您可以将它们分成两个流

const combined=combineLatest(a21$, a22$, a23$)

const count=combined.pipe(count())

const c2$=combined.pipe(
    map(([a, b ,c]) => {
        return this.httpClient.get(`http://example.com/${a}${b}${c}`);
    })
)
// get the counts
count.subscribe(console.log)

推荐阅读