mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-06-01 23:45:28 +00:00
22 lines
582 B
Kotlin
22 lines
582 B
Kotlin
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()
|
|
}
|