Polling is a widespread mechanism where a client application periodically fetches data from a server to keep its UI up to date with real-time. In this article we’ll see how polling in Angular using RxJS can be accomplished and how mixing the different RxJS operators can create a robust solution for this case. Let’s jump to it!
Use Cases
In the next steps we’ll be seeing two different use cases that happen quite commonly in web apps.
Polling until positive response from server
At some point in our app we have to perform an HTTP request until a certain condition is met, for example in this case until the task status is true.
timer(500, 1000).pipe( mergeMap(t => this.taskService.getStatus(taskId)), filter(response => response.status), take(1) ).subscribe(() => { })
In the above code we make an HTTP request checking if the task status is true. If it is, then we stop polling , otherwise we keep polling every second. In the subscribe you can your own logic, just remember that it will run once we stop polling.
Polling until positive response from server then perform another request
It can happen that we have to perform an HTTP request but first we need to check if another endpoint’s status is true.
timer(500, 1000).pipe( mergeMap(t => this.taskService.getStatus(taskId)), filter(response => response.status), take(1), switchMap(() => this.orderService.getOrders()) ).subscribe(() => { })
In the above code we make an HTTP request checking if the task status is true. If it is, then we make another HTTP request to fetch some orders, otherwise we keep polling. This time in the subscribe we’ll have the result of the previous request (as long as there is) and again you can run your own logic.
Conclusion
As you can see it’s quite easy to do polling in Angular, and using RxJS, you can implement efficient and straightforward polling mechanisms. In the above examples we applied a slight delay to perform the first http request, but if you don’t need it you may use interval operator.