Last active
October 18, 2022 21:12
-
-
Save ToastShaman/0dc59463a08b4b71c6a8182e1af75c67 to your computer and use it in GitHub Desktop.
A simple retry mechanism in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun <R> retry( | |
maxAttempts: Int, | |
action: () -> R | |
): R { | |
require(maxAttempts > 0) { "maxAttempts must be greater than 0" } | |
return runCatching(action).getOrElse { | |
val leftAttempts = maxAttempts.dec() | |
if (leftAttempts == 0) throw it | |
retry(leftAttempts, action) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment