Last active
March 13, 2022 12:00
-
-
Save davidgomesdev/949c1fb1a7fbd74c56342fb59bc2c111 to your computer and use it in GitHub Desktop.
Kotlin Retry utils
This file contains hidden or 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
// Inspired by `Flow.retry` | |
inline fun <T> retryUntil( | |
block: () -> T, | |
isValid: (T) -> Boolean, | |
beforeRetry: () -> Unit = {}, | |
afterRetry: (T) -> Unit = {}, | |
): T { | |
var value = block() | |
while (!isValid(value)) { | |
beforeRetry() | |
value = block() | |
afterRetry(value) | |
} | |
return value | |
} | |
inline fun <T> retry( | |
times: Int, | |
block: () -> Result<T>, | |
beforeRetry: (Int) -> Unit = {}, | |
afterRetry: (Throwable) -> Unit = {}, | |
retryExceeded: (Int) -> Unit = {}, | |
): Result<T> { | |
var value = block() | |
if (value.isSuccess) return value | |
repeat(times) { i -> | |
beforeRetry(i + 1) | |
value = block() | |
if (value.isFailure) | |
afterRetry(value.exceptionOrNull()!!) | |
} | |
retryExceeded(times) | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment