Skip to content

Instantly share code, notes, and snippets.

@cjgaliana
Created April 11, 2021 08:43
Show Gist options
  • Save cjgaliana/fc5c919c7c2e89778a0d22390ece3aa0 to your computer and use it in GitHub Desktop.
Save cjgaliana/fc5c919c7c2e89778a0d22390ece3aa0 to your computer and use it in GitHub Desktop.
Retry Logic for Kotlin and Couroutines
package com.cjgaliana.utils
import kotlinx.coroutines.delay
import timber.log.Timber
suspend fun <T> retryWhen(
predicate: (cause: Exception, attempt: Int) -> Boolean,
delayInMilliseconds: Long = 0,
block: suspend () -> T
): T {
var attemptNumber = 0
var exception: Exception? = null
do {
try {
return block()
} catch (ex: Exception) {
Timber.e(ex, "Failed attempt $attemptNumber")
exception = ex
attemptNumber++
if(delayInMilliseconds > 0) {
delay(delayInMilliseconds)
}
}
} while (predicate(exception!!, attemptNumber))
throw exception
}
suspend fun <T> retry(
maxRetries: Int,
block: () -> T
): T {
var attemptNumber = 0
var exception: Throwable? = null
do {
try {
return block()
} catch (ex: Exception) {
Timber.e(ex, "Failed attempt $attemptNumber of $maxRetries")
exception = ex
attemptNumber++
}
} while (attemptNumber< maxRetries)
throw exception!!
}
// How to use it
suspend fun doSomething() {
val shouldRetry : (cause: Exception, attempt: Int) -> Boolean = { cause, attempt ->
cause is ApolloHttpException && attempt < REQUEST_RETRY_LIMIT
}
retryWhen(shouldRetry) {
// do somehting here that can fail and you want to rety
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment