Http requests polling like a hero with RxJS


There are situations when you cannot simply fetch data once and present it in your application, since it’s highly possible that it changes over time ⏳. One solution is to make use of web sockets, however a simple polling mechanism might be a good enough approach ✔️. In this blog post I’ll introduce two custom RxJS operators encapsulating the polling logic, which allow to accomplish the goal in a far more elegant way than the imperative approach with setInterval or setTimeout functions 👍.


Long polling

If you simply wish to perform an http request every n seconds ⏰, you can use the following custom RxJS operator:

The operator takes the source stream and switches to it every n seconds ⏰ which triggers an http request.

Exemplary usage:

Don’t forget to handle possible errors, otherwise the resulting stream dies out once an error has occurred 😢.


Conditional polling

Sometimes you want to keep polling until a given condition is met. For example, a response body may contain a flag 🚩(e.g. inProgress field) based on which you decide when to stop the mechanism. In addition, you may wish to limit the number of http requests 🚫. The following custom RxJS operator allows to accomplish such goal:

The operator works a little bit similar to the poll operator, however if the number of attempts has reached the limit, an error is thrown which results in the output stream being unsubscribed. Moreover, you only make http requests until the given condition defined as responsePredicate is not met.

Exemplary usage:

In order to simply switch the inProgress flag, I used the of operator to simulate an http request stream. In the above example, the flag is toggled before the attempts limit is reached, therefore the resulting stream completes with the desired http response. If you allow to reach the limit by changing the setTimeout delay, the error will be thrown 🔥.


Conclusions

In this blog posts I presented two custom RxJS operators which allow you to perform http requests polling in a very convenient manner. I believe that accomplishing the goal in that way is far more readable and declarative than using setInterval or setTimeout functions.

Feel free to play around with the example:

I hope you liked the post and learned something new 👍 If so, please give me some applause 👏

JavaScript everyday

Wojciech Trawiński

Written by

Doing awesome things using JavaScript

JavaScript everyday

Improve your JavaScript skills everyday!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade