Taipei, Taiwan

RxJava: backoff on retry

Andrew Chen
1 min readApr 3, 2019

I used to use linear backoff instead of exponential backoff on retry, because I thought that would be lower overhead.

You should see the following code snippet for linear backoff often:

obs.retryWhen { attempts ->
attempts.zipWith(Observable.range(1, Int.MAX_VALUE)) { _, i -> i }
.flatMap { i -> Observable.timer(i, TimeUnit.SECONDS) }
}

or

obs.retryWhen { attempts ->
val counter = AtomicInteger();
attempts.takeWhile { counter.getAndIncrement() < Int.MAX_VALUE }
.flatMap { i -> Observable.timer(i, TimeUnit.SECONDS) }
}

I really used to use this kind of code, so I made a Transformer for it, recently I found there is no this kinda code snippet on the internet, that’s what I want to share:

You can easily apply backoff on retry by the following:

obs.compose(backoff(10) { e, _ ->
e is IOException
})
.subscribe()

That means it will retry for IOException for 10 times with interval, that would be 1s, 2s, 3s, … until 10s.

We can make it more flexible:

--

--

No responses yet