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

后端 未结 14 2294
别那么骄傲
别那么骄傲 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:06

    You can add a delay in the Observable returned in the retryWhen Operator

              /**
     * Here we can see how onErrorResumeNext works and emit an item in case that an error occur in the pipeline and an exception is propagated
     */
    @Test
    public void observableOnErrorResumeNext() {
        Subscription subscription = Observable.just(null)
                                              .map(Object::toString)
                                              .doOnError(failure -> System.out.println("Error:" + failure.getCause()))
                                              .retryWhen(errors -> errors.doOnNext(o -> count++)
                                                                         .flatMap(t -> count > 3 ? Observable.error(t) : Observable.just(null).delay(100, TimeUnit.MILLISECONDS)),
                                                         Schedulers.newThread())
                                              .onErrorResumeNext(t -> {
                                                  System.out.println("Error after all retries:" + t.getCause());
                                                  return Observable.just("I save the world for extinction!");
                                              })
                                              .subscribe(s -> System.out.println(s));
        new TestSubscriber((Observer) subscription).awaitTerminalEvent(500, TimeUnit.MILLISECONDS);
    }
    

    You can see more examples here. https://github.com/politrons/reactive

提交回复
热议问题