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/2c72aa84d13f1b3c0ecd77f6d9b5697e to your computer and use it in GitHub Desktop.
Save pamartineza/2c72aa84d13f1b3c0ecd77f6d9b5697e to your computer and use it in GitHub Desktop.
// 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 limit of retries is reached error is thrown 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 (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