rxjava: Can I use retry() but with delay?

后端 未结 14 2258
别那么骄傲
别那么骄傲 2020-11-28 18:25

I am using rxjava in my Android app to handle network requests asynchronously. Now I would like to retry a failed network request only after a certain time has passed.

14条回答
  •  攒了一身酷
    2020-11-28 18:57

    Now with RxJava version 1.0+ you can use zipWith to achieve retry with delay.

    Adding modifications to kjones answer.

    Modified

    public class RetryWithDelay implements 
                                Func1, Observable> {
    
        private final int MAX_RETRIES;
        private final int DELAY_DURATION;
        private final int START_RETRY;
    
        /**
         * Provide number of retries and seconds to be delayed between retry.
         *
         * @param maxRetries             Number of retries.
         * @param delayDurationInSeconds Seconds to be delays in each retry.
         */
        public RetryWithDelay(int maxRetries, int delayDurationInSeconds) {
            MAX_RETRIES = maxRetries;
            DELAY_DURATION = delayDurationInSeconds;
            START_RETRY = 1;
        }
    
        @Override
        public Observable call(Observable observable) {
            return observable
                    .delay(DELAY_DURATION, TimeUnit.SECONDS)
                    .zipWith(Observable.range(START_RETRY, MAX_RETRIES), 
                             new Func2() {
                                 @Override
                                 public Integer call(Throwable throwable, Integer attempt) {
                                      return attempt;
                                 }
                             });
        }
    }
    

提交回复
热议问题