Retrying the request using Retrofit 2

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

    I've made custom implementation of the Callback interface, you can pretty much use it in place of original callback. If call is successful, the onResponse() method is called. If after retrying for set amount of repetitions call fails, onFailedAfterRetry() is called.

    public abstract class BackoffCallback implements Callback {
    private static final int RETRY_COUNT = 3;
    /**
     * Base retry delay for exponential backoff, in Milliseconds
     */
    private static final double RETRY_DELAY = 300;
    private int retryCount = 0;
    
    @Override
    public void onFailure(final Call call, Throwable t) {
        retryCount++;
        if (retryCount <= RETRY_COUNT) {
            int expDelay = (int) (RETRY_DELAY * Math.pow(2, Math.max(0, retryCount - 1)));
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    retry(call);
                }
            }, expDelay);
        } else {
            onFailedAfterRetry(t);
        }
    }
    
    private void retry(Call call) {
        call.clone().enqueue(this);
    }
    
    public abstract void onFailedAfterRetry(Throwable t);
    
    }
    

    https://gist.github.com/milechainsaw/811c1b583706da60417ed10d35d2808f

提交回复
热议问题