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

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

    This example works with jxjava 2.2.2:

    Retry without delay:

    Single.just(somePaylodData)
       .map(data -> someConnection.send(data))
       .retry(5)
       .doOnSuccess(status -> log.info("Yay! {}", status);
    

    Retry with delay:

    Single.just(somePaylodData)
       .map(data -> someConnection.send(data))
       .retryWhen((Flowable f) -> f.take(5).delay(300, TimeUnit.MILLISECONDS))
       .doOnSuccess(status -> log.info("Yay! {}", status)
       .doOnError((Throwable error) 
                    -> log.error("I tried five times with a 300ms break" 
                                 + " delay in between. But it was in vain."));
    

    Our source single fails if someConnection.send() fails. When that happens, the observable of failures inside retryWhen emits the error. We delay that emission by 300ms and send it back to signal a retry. take(5) guarantees that our signaling observable will terminate after we receive five errors. retryWhen sees the termination and doesn't retry after the fifth failure.

提交回复
热议问题