Skip to content

Instantly share code, notes, and snippets.

@necatisozer
Created October 1, 2023 15:37
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 necatisozer/bc1cb2b94435b98c1418ae01fdb808dc to your computer and use it in GitHub Desktop.
Save necatisozer/bc1cb2b94435b98c1418ae01fdb808dc to your computer and use it in GitHub Desktop.
ExponentialRetry.kt
private suspend fun <T> exponentialRetry(
maxTries: Int = Int.MAX_VALUE,
initialDelay: Long = Long.MAX_VALUE,
retryFactor: Int = Int.MAX_VALUE,
block: suspend () -> T
): T? {
var currentDelay = initialDelay
var retryAttempt = 1
do {
runCatching {
delay(currentDelay)
block()
}
.onSuccess {
Log.d(TAG, "Retry succeeded")
return@onSuccess;
}
.onFailure { throwable ->
Log.e(
TAG,
"Retry Failed -- Cause: ${throwable.cause} -- Message: ${throwable.message}"
)
}
currentDelay *= retryFactor
retryAttempt++
} while (retryAttempt < maxTries)
return block() // last attempt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment