How to retry HTTP requests with OkHttp/Retrofit?

后端 未结 13 746
一向
一向 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 10:04

    I have play a lot with this problem trying to find how is the best way to retry Retrofit requests. I am using Retrofit 2 so my solution is for Retrofit 2. For Retrofit 1 you have to use Interceptor like the accepted answer here. The answer of @joluet is correct but he did not mention that retry method need to be called before .subscribe(onComplete, onError) method. This is very important otherwise the request wouldn't be retried again like @pocmo mentioned in @joluet answer. Here is my example:

    final Observable> newsDetailsObservable = apiService.getCandidateNewsItem(newsId).map((newsDetailsParseObject) -> {
                        return newsDetailsParseObject;
                    });
    
    newsDetailsObservable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .retry((integer, throwable) -> {
                    //MAX_NUMBER_TRY is your maximum try number
                    if(integer <= MAX_NUMBER_TRY){
                        return true;//this will retry the observable (request)
                    }
                    return false;//this will not retry and it will go inside onError method
                })
                .subscribe(new Subscriber>() {
                    @Override
                    public void onCompleted() {
                        // do nothing
                    }
    
                    @Override
                    public void onError(Throwable e) {
                       //do something with the error
                    }
    
                    @Override
                    public void onNext(List apiNewsDatum) {
                        //do something with the parsed data
                    }
                });
    

    apiService is my RetrofitServiceProvider object.

    BTW : I am using Java 8 so a lot of lambda expressions are inside the code.

提交回复
热议问题