diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c9d5307274..3daac0f5929 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 0.8.5 +* `Common`: + * `repeatOnFailure` + ## 0.8.4 * `Ktor`: diff --git a/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/RepeatOnFailure.kt b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/RepeatOnFailure.kt new file mode 100644 index 00000000000..6a396499fc7 --- /dev/null +++ b/common/src/commonMain/kotlin/dev/inmo/micro_utils/common/RepeatOnFailure.kt @@ -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 repeatOnFailure( + times: Int, + crossinline onEachFailure: (Throwable) -> Unit = {}, + crossinline action: (Int) -> R +): Optional { + repeat(times) { + runCatching { + action(it) + }.onFailure(onEachFailure).onSuccess { + return Optional.presented(it) + } + } + return Optional.absent() +}