Skip to content

Instantly share code, notes, and snippets.

@pamartineza
Last active September 8, 2018 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pamartineza/71fa7c843ad7ef949a36301ab312bfcb to your computer and use it in GitHub Desktop.
Save pamartineza/71fa7c843ad7ef949a36301ab312bfcb to your computer and use it in GitHub Desktop.
Example of Exponential Backoff using RxJava 2 retryWhen() with interruption for UnknownHostException
// Our function Zips error emissions with a range to limit them to 3,
// and emits a 0L with a power of 2 based delay.
// If emitted error is an UnknownHostException no more retries are done and
// error is thrown, otherwise if the limit of retries is reached error is
// thrown too, in both cases to ensure it reaches our subscribe block
val RETRIES_LIMIT = 3
webservice.getRequestSingle()
.retryWhen { errors: Flowable<Throwable> ->
errors.zipWith(
Flowable.range(1, RETRIES_LIMIT + 1)
Bifunction<Throwable, Int, Int> { error: Throwable, retryCount: Int ->
if (error is UnknownHostException || retryCount > RETRIES_LIMIT) {
throw error
} else {
retryCount
}
}
).flapMap { retryCount: Int ->
Flowable.timer(
Math.pow(2.toDouble(), retryCount.toDouble()).toLong(),
TimeUnit.SECONDS
)
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ data ->
//refreshScreenWithData
}, { error ->
//handle error
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment