Retrying the request using Retrofit 2

后端 未结 7 930
天涯浪人
天涯浪人 2020-12-12 17:35

How can I add retry functionality to the requests sent by Retrofit 2 library. Something like:

service.listItems().enqueue(new Callback>         


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-12 18:01

    ashkan-sarlak answer work great and i'm just try to make it up to date.

    From retrofit 2.1

    onFailure(Throwable t) 
    

    Change to

    onFailure(Call call, Throwable t)
    

    So this make it so easy now.just create CallbackWithRetry.java like this

    public abstract class CallbackWithRetry implements Callback {
    
        private static final int TOTAL_RETRIES = 3;
        private static final String TAG = CallbackWithRetry.class.getSimpleName();
        private int retryCount = 0;
    
        @Override
        public void onFailure(Call call, Throwable t) {
            Log.e(TAG, t.getLocalizedMessage());
            if (retryCount++ < TOTAL_RETRIES) {
                Log.v(TAG, "Retrying... (" + retryCount + " out of " + TOTAL_RETRIES + ")");
                retry(call);
            }
        }
    
        private void retry(Call call) {
            call.clone().enqueue(this);
        }
    }
    

    That's all! you can simply use it like this

    call.enqueue(new CallbackWithRetry() {
    
            @Override
            public void onResponse(@NonNull Call call, @NonNull retrofit2.Response response) {
                //do what you want
            }
            @Override
            public void onFailure(@NonNull Call call, @NonNull Throwable t) {
                super.onFailure(call,t);
                //do some thing to show ui you trying
                //or don't show! its optional
            }
        });
    

提交回复
热议问题