repeatOnFailure

This commit is contained in:
InsanusMokrassar 2021-11-26 19:45:59 +06:00
parent 6763e5c4c6
commit 527a2a91ac
2 changed files with 24 additions and 0 deletions

View File

@ -2,6 +2,9 @@
## 0.8.5
* `Common`:
* `repeatOnFailure`
## 0.8.4
* `Ktor`:

View File

@ -0,0 +1,21 @@
package dev.inmo.micro_utils.common
/**
* Executes the given [action] until getting of successful result specified number of [times].
*
* A zero-based index of current iteration is passed as a parameter to [action].
*/
inline fun <R> repeatOnFailure(
times: Int,
crossinline onEachFailure: (Throwable) -> Unit = {},
crossinline action: (Int) -> R
): Optional<R> {
repeat(times) {
runCatching {
action(it)
}.onFailure(onEachFailure).onSuccess {
return Optional.presented(it)
}
}
return Optional.absent()
}