Skip to content

Instantly share code, notes, and snippets.

@raghunandankavi2010
Created July 14, 2020 10:57
Show Gist options
  • Save raghunandankavi2010/3a9fbefc04a256caeb1ee15070b50b1e to your computer and use it in GitHub Desktop.
Save raghunandankavi2010/3a9fbefc04a256caeb1ee15070b50b1e to your computer and use it in GitHub Desktop.
suspend fun <T> retryIO(
times: Int = Int.MAX_VALUE,
initialDelay: Long = 100, // 0.1 second
maxDelay: Long = 1000, // 1 second
factor: Double = 2.0,
block: suspend () -> T): T
{
var currentDelay = initialDelay
repeat(times - 1) {
try {
return block()
} catch (e: IOException) {
// you can log an error here and/or make a more finer-grained
// analysis of the cause to see if retry is needed
}
delay(currentDelay)
currentDelay = (currentDelay * factor).toLong().coerceAtMost(maxDelay)
}
return block() // last attempt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment