Easily Retrying Network Requests on Android (with Retrofit 2)

Pallav Ahooja
Shuttl
Published in
2 min readJun 1, 2016

When we are developing for mobile , network is one of the many unique challenges. We have a intermittent , low bandwidth and high latency connection — your network calls can and will fail randomly.
This problem is accentuated even more here in India with patchy 2G/3G connection,especially for our users who may book their Shuttls on roads or at places with low network connectivity.

Hence it is a good idea to add a retry ( and back-off) policy , for at least the important idempotent network calls. It makes for a better user experience.

If you know Android Development or have worked with Android Developer , chances are that you might have heard of Retrofit.
It is one of the best networking libraries for Android ( and JAVA too ) out there. It provides a powerful and flexible framework for authenticating and interacting with APIs.

Now , retrofit does not come with retry support by default (although it was in their spec for their 2.0 release).

If you are using Rx in your android app ,you can add the Retrofit Rx adapter and use RxJava observables for retrying.

(https://github.com/ReactiveX/RxJava/wiki/Error-Handling-Operators )

If you are not using Rx it is not that straightforward and you will have to check for failure, clone and enqueue the call manually for each network call.

That sounds like some work and boilerplate code.

So, I tried a quick and easy way to accomplish this. Here’s what I did —

Other possible ways I could have accomplished this -

  • OKHttp Interceptors
  • Rx Observables

To do next

  • Even more simpler way to add retry ( annotation based?)
  • Have a configurable retry policy , with wait time and back offs too.

More on this and other topics to follow soon.

Thoughts, suggestions welcome.

--

--