Skip to content

Instantly share code, notes, and snippets.

@quentin41500
Last active February 12, 2019 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quentin41500/4a128c39e0507e3b9d469ddb06c95e7d to your computer and use it in GitHub Desktop.
Save quentin41500/4a128c39e0507e3b9d469ddb06c95e7d to your computer and use it in GitHub Desktop.
/**
* Execute [block] and operate [predicate] on returned value. Each retries can be separated by
* [delay] if necessary.
*
* @param count Number of tries before failing.
* @param delay Delay between retries
* @param block Code to execute
* @param predicate Predicate to execute.
*/
suspend fun <T> retryWithPredicate(
count: Int = 5,
delay: Long = 0,
block: suspend (Int) -> T,
predicate: suspend (T) -> Boolean
): T {
for (i in 1..count) {
count.takeIf { it > 1 }.run { delay(delay) }
block(i).takeIf { predicate(it) }?.run { return this }
}
throw RetriesExceededException()
}
/**
* Thrown when number of retries has been exceeded.
*/
class RetriesExceededException : Exception()
@DiegoAnfuso
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment