mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-12-18 14:47:15 +00:00
repeatOnFailure
This commit is contained in:
parent
6763e5c4c6
commit
527a2a91ac
@ -2,6 +2,9 @@
|
||||
|
||||
## 0.8.5
|
||||
|
||||
* `Common`:
|
||||
* `repeatOnFailure`
|
||||
|
||||
## 0.8.4
|
||||
|
||||
* `Ktor`:
|
||||
|
@ -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()
|
||||
}
|
Loading…
Reference in New Issue
Block a user