Skip to content

Instantly share code, notes, and snippets.

@iamkingalvarado
Created July 28, 2020 01:21
Show Gist options
  • Save iamkingalvarado/54a07a8c0dc1667ae3867c6b0c5c3f65 to your computer and use it in GitHub Desktop.
Save iamkingalvarado/54a07a8c0dc1667ae3867c6b0c5c3f65 to your computer and use it in GitHub Desktop.
suspend fun <T> retry(
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: Exception) {
// 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 null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment