Skip to content

Instantly share code, notes, and snippets.

@davidgomesdev
Last active March 13, 2022 12:00
Show Gist options
  • Save davidgomesdev/949c1fb1a7fbd74c56342fb59bc2c111 to your computer and use it in GitHub Desktop.
Save davidgomesdev/949c1fb1a7fbd74c56342fb59bc2c111 to your computer and use it in GitHub Desktop.
Kotlin Retry utils
// 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