Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Created June 16, 2023 12:45
Show Gist options
  • Save Andrew0000/a1c108576b380d47e34abe9c11d02281 to your computer and use it in GitHub Desktop.
Save Andrew0000/a1c108576b380d47e34abe9c11d02281 to your computer and use it in GitHub Desktop.
Retrying coroutines + additional onError() callback
import kotlinx.coroutines.delay
import kotlin.coroutines.cancellation.CancellationException
@Throws
suspend fun <T> retrying(
fallbackValue: T? = null,
tryCnt: Int = 3,
intervalMillis: (attempt: Int) -> Long = { 2000L * it },
onError: suspend (Throwable) -> Unit = {},
retryCheck: (Throwable) -> Boolean = networkRetryCheck,
block: suspend () -> T,
): T {
try {
val retryCnt = tryCnt - 1
repeat(retryCnt) { attempt ->
try {
return block()
} catch (e: Exception) {
if (e !is CancellationException) {
onError(e)
}
if (e is CancellationException || !retryCheck(e)) {
throw e
}
}
delay(intervalMillis(attempt + 1))
}
return block()
} catch (e: Exception) {
if (e !is CancellationException) {
onError(e)
}
if (e is CancellationException) {
throw e
}
return fallbackValue ?: throw e
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment