Conditionally Retry Asynchronous Network Calls on Android Using Retrofit 2

Johnny Tordgeman
2 min readMay 18, 2018

--

Photo by Angela Compagnone on Unsplash

Developing a mobile application comes with its own set of issues that you need to take care of. One of those issues is the possibility of a lousy network connection. An unstable network can cause your app’s API calls to fail, resulting in a poor user experience if not handled right.

One way to handle such case is to use a Retrofit/OKHTTP feature called Interceptors to retry the failed request. There is one catch though — Interceptors are designed to be as simple and logic-less as possible, and if you do decide to add more logic to an Interceptor, and make a call to a server to get some data to decide what to do next based on that — you would have to do it synchronously.

Since one of the SDKs I use is callback based and cannot be called synchronously, I had to come up with a different approach. While searching the usual StackOverflow threads looking for a direction, I came across this awesome post by Pallav Ahooja called Easily Retrying Network Requests on Android With Retrofit 2. The post demonstrates how to achieve a retry using a new object called RetryableCallback which implements OKHTTP’s callback object and add some logic to it to handle retry. This approach works great if you want to base your retry on counters, meaning if a request failed retry it X times. I needed to base my retry logic on data from a callback based function and as such i needed to make some changes to the solution, which I’m going to list right here…

The APIHelper class

The first class i created is APIHelper, which exposes two functions:

  • enqueueWithRetry — replaces Retrofit’s enqueue function for async methods.
  • isCallSucess — the logic that determines if a server call was successful or not.

The code for this class is as follows:

Looking at the function, we can see the real magic happens inside the RetryableCallback class which is in charge of handling the call and its responses.

The RetryableCallback class

The heart of this method is the RetryableCallback class, which its implementation is as follows:

Once everything is in place, you can use the new API using the following code snippet:

And there you have it. A relatively simple way of performing retry for an asynchronous Retrofit call based on pre-defined conditions. The RetryableCallback class can be even further enhanced by adding time outs, secondary rules etc. making your request retry logic smarter and more efficient :)

🎉 Special thanks to Guy Bary and Yaron Schwimmer for all their help with this post!

Originally published at www.perimeterx.com.

--

--

Johnny Tordgeman
Johnny Tordgeman

Written by Johnny Tordgeman

Senior Backend Engineer - Blockchains @FireblocksHQ | Loves to talk about Rust 🦀 / TypeScript / JavaScript / WebAssembly | Web3 is AWESOME

Responses (1)