Regularly Polling API with RxJava & Retrofit

In Monitor for EnergyHive & Efergy Engage, I have to regularly poll the EnergyHive API to retrieve the latest energy readings. In previous versions of the app, I've worked with Handlers and other Android frameworks to make a request every 5 seconds while the app is open. Even though this works reliably, the code is difficult to read and not very maintainable.

For this reason, in the 2018 rewrite of the app, I have used RxJava and Retrofit for the AP. This handles much of the heavy lifting behind the timer that calls the API. The following methods show how I am using ReactiveX features to poll the API at a regular time interval, with requests cancelled if they take longer than 5 seconds. Start polling is called onResume, and stop polling is called onPause.

The above code is just a guideline, in fact, there are probably better ways of doing this. And, to copy the code, you will need to set up your Retrofit API like I have done. Some of this setup is in the following gist.

I'm hoping this post could become a resource for people looking to do the same as me. If you find another method which utilises RxJava, drop a comment and I'll append it to the post with credits to you.