I am new to Android and I am trying to figure out the best way to handle the situation when a user does not have a network connection. I am using Retrofit2 with OkHttp and I have tried multiple solutions.
First approach:
OkHttp interceptor:
new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = chain.proceed(request);
private final SuperActivityToast warningToast = new
SuperActivityToast(currentActivity, new Style(), Style.TYPE_BUTTON).setIndeterminate(true);
warningToast.setText("Currently offline").show;
while (!response.isSuccessful()) {
// retry the request
response = chain.proceed(request);
}
// otherwise just pass the original response on
return response;
}
}
So basically I keep retrying a request up until the user has a network connection (this is the basic idea, I will implement a check to differentiate between the case when the user has no network and when the issue comes from the server), but I am aware that it is not efficient. Also the while loop is never accessed (I've used debugging mode with breakpoints to check), the code stops at: Response response = chain.proceed(request);
, at this part the request is reloaded, and even tho' it fails again the interceptor is never reaccessed, without any errors in the console.
Second approach:
I have used this example: Retrying the request using Retrofit 2 to implement a toast with a button for the user to retry a failed request manually but in this situation I've met a barrier: If an activity has multiple requests a toast with a retry button will be shown for the user to retry each request separately.
Any other ways I have missed? The main question is: What is the best way to check for user network disconnection and allow the user to retry the request or for us to automatically retry the failed requests?