Created
May 6, 2021 13:00
-
-
Save devrath/e86d591e0e03732f5050bc8a798c60b6 to your computer and use it in GitHub Desktop.
Retry mechanism for OKHTTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mpl.network.modules.interceptors; | |
import android.os.Handler; | |
import android.util.Log; | |
import java.io.IOException; | |
import okhttp3.Interceptor; | |
import okhttp3.Request; | |
import okhttp3.Response; | |
public class RetryInterceptor implements Interceptor { | |
private static final String TAG = "NetworkLib: " + "RetryInterceptor"; | |
private static final int NUMBER_OF_RETRIES = 4; | |
private static final double RETRY_DELAY = 300; | |
@Override | |
public Response intercept(Chain chain) throws IOException { | |
Request request = chain.request(); | |
// try the request | |
final Response[] response = {chain.proceed(request)}; | |
int tryCount = 0; | |
while (!response[0].isSuccessful() && tryCount < NUMBER_OF_RETRIES) { | |
int expDelay = (int) (RETRY_DELAY * Math.pow(2, Math.max(0, NUMBER_OF_RETRIES - 1))); | |
tryCount++; | |
new Handler().postDelayed(() -> { | |
try { | |
response[0] = chain.call().clone().execute(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}, expDelay); | |
} | |
// otherwise just pass the original response on | |
return response[0]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment