RXJS polling without recursion

喜欢而已 提交于 2020-12-13 11:41:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!