Last active
February 12, 2019 19:35
-
-
Save quentin41500/4a128c39e0507e3b9d469ddb06c95e7d to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍