RXJS 轮询无递归 [英] RXJS polling without recursion
问题描述
服务器正在同时处理多个请求.调用服务以检查每个请求的状态.服务接受 id 列表并将给出每个 id 的状态如下
Server is processing multiple request at the same time. Call the service to check the status of each request. Service accepts list of ids and will give status of each id as following
{ id: number, status: number}; Status 1 is pending and 2 is complete
需要轮询所有待处理的请求 id,直到所有请求完成
Need to poll on all the pending request ids until all requests are complete
我有以下递归解决方案,但需要一个简洁的 RXJS 解决方案
I have a following recursive solution but need a concise RXJS solution for it
poll(requestIds: Array<number>): void {
if (requestIds.length > 0) {
callService(requestIds).subscribe((response) => {
const pending = response.reduce((result, request) => {
if (request.status === 1) { result.push(request.id); }
}, []);
setTimeout(() => poll(pending), 5000);
});
}
}
在上面的例子中没有提到的是 clearTimeout 和在轮询停止时被清除的订阅列表.我知道这可以通过 repeatWhen 和 takeWhile 来实现
Not mentioned in the above example is the clearTimeout and list of subscription which gets cleared when polling stops. I know that this could be acheived with repeatWhen and takeWhile
推荐答案
这是一个实现你递归的 rxjs 流:
This is an rxjs stream that achieves your recursion:
callService(ids).pipe(
expand(reqs => reqs.length === 0
? empty()
: callService(
reqs.filter(req => req.status === 1).map(req => req.id)
).pipe(delay(1000))
)
).subscribe();
在这里你可以看到一个演示:https://stackblitz.com/edit/rxjs-aaxiru
Here you can see a demonstration: https://stackblitz.com/edit/rxjs-aaxiru
这篇关于RXJS 轮询无递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!