问题
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
Need to poll on all the pending request ids until all requests are complete
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);
});
}
}
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
回答1:
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();
Here you can see a demonstration: https://stackblitz.com/edit/rxjs-aaxiru
来源:https://stackoverflow.com/questions/54046860/rxjs-polling-without-recursion