Retrying the request using Retrofit 2

后端 未结 7 923
天涯浪人
天涯浪人 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:17

    I did something quite similar to Ashkan Sarlak, but since Retrofit 2.1 passes the Call into the onFailure method, you can simplify to one CallbackWithRetry abstract class. See:

    public abstract class CallbackWithRetry implements Callback {
    
    
    
     private static final String TAG = "CallbackWithRetry";
    
      private int retryCount = 0;
    
      private final Logger logger;
      private final String requestName;
      private final int retryAttempts;
    
      protected CallbackWithRetry(@NonNull Logger logger, @NonNull String requestName, int retryAttempts) {
        this.logger = logger;
        this.requestName = requestName;
        this.retryAttempts = retryAttempts;
      }
    
      @Override
      public void onFailure(Call call, Throwable t) {
        if (retryCount < retryAttempts) {
          logger.e(TAG, "Retrying ", requestName, "... (", retryCount, " out of ", retryAttempts, ")");
          retry(call);
    
          retryCount += 1;
        } else {
          logger.e(TAG, "Failed request ", requestName, " after ", retryAttempts, " attempts");
        }
      }
    
      private void retry(Call call) {
        call.clone().enqueue(this);
      }
    }
    

提交回复
热议问题