Issue
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?
Solution
There can be two solutions, which suits you better it is up to you to decide:
1) you can use Broadcast Receiver to detect network connection change, and send broadcast to all interested fragments or activities to do network call automatically when device gets internet connection. detailed tutorial here
2) You can use RxJava (I use this approach), with this simple library you get callback in observable when network be
Github of the library - RxNetwork
Answered By - Misha Akopov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.