How to retry HTTP requests with OkHttp/Retrofit?

后端 未结 13 743
一向
一向 2020-12-07 09:04

I am using Retrofit/OkHttp (1.6) in my Android project.

I don\'t find any request retry mechanism built-in to either of them. On searching more, I read OkHttp seems

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 09:51

    Just want to share my version. It uses rxJava retryWhen method. My version retries connection every N=15 sec and almost immediately emit retry when internet connection recover.

    public class RetryWithDelayOrInternet implements Function, Flowable> {
    public static boolean isInternetUp;
    private int retryCount;
    
    @Override
    public Flowable apply(final Flowable attempts) {
        return Flowable.fromPublisher(s -> {
            while (true) {
                retryCount++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    attempts.subscribe(s);
                    break;
                }
                if (isInternetUp || retryCount == 15) {
                    retryCount = 0;
                    s.onNext(new Object());
                }
            }
        })
                .subscribeOn(Schedulers.single());
    }}
    

    And you should use it before .subscribe like this:

    .retryWhen(new RetryWithDelayOrInternet())
    

    You should manually change isInternetUp field

    public class InternetConnectionReceiver extends BroadcastReceiver {
    
    
    @Override
    public void onReceive(Context context, Intent intent) {
        boolean networkAvailable = isNetworkAvailable(context);
        RetryWithDelayOrInternet.isInternetUp = networkAvailable;
    }
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }}
    

提交回复
热议问题