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

后端 未结 14 2214
别那么骄傲
别那么骄傲 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 19:15

    For Kotlin & RxJava1 version

    class RetryWithDelay(private val MAX_RETRIES: Int, private val DELAY_DURATION_IN_SECONDS: Long)
        : Function1<Observable<out Throwable>, Observable<*>> {
    
        private val START_RETRY: Int = 1
    
        override fun invoke(observable: Observable<out Throwable>): Observable<*> {
            return observable.delay(DELAY_DURATION_IN_SECONDS, TimeUnit.SECONDS)
                .zipWith(Observable.range(START_RETRY, MAX_RETRIES),
                    object : Function2<Throwable, Int, Int> {
                        override fun invoke(throwable: Throwable, attempt: Int): Int {
                            return attempt
                        }
                    })
        }
    }
    
    0 讨论(0)
  • 2020-11-28 19:18

    Simply do it like this:

                      Observable.just("")
                                .delay(2, TimeUnit.SECONDS) //delay
                                .flatMap(new Func1<String, Observable<File>>() {
                                    @Override
                                    public Observable<File> call(String s) {
                                        L.from(TAG).d("postAvatar=");
    
                                        File file = PhotoPickUtil.getTempFile();
                                        if (file.length() <= 0) {
                                            throw new NullPointerException();
                                        }
                                        return Observable.just(file);
                                    }
                                })
                                .retry(6)
                                .subscribe(new Action1<File>() {
                                    @Override
                                    public void call(File file) {
                                        postAvatar(file);
                                    }
                                }, new Action1<Throwable>() {
                                    @Override
                                    public void call(Throwable throwable) {
    
                                    }
                                });
    
    0 讨论(0)
提交回复
热议问题