Created
June 16, 2023 12:45
-
-
Save Andrew0000/a1c108576b380d47e34abe9c11d02281 to your computer and use it in GitHub Desktop.
Retrying coroutines + additional onError() callback
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
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