Skip to content

Commit

Permalink
Retry
Browse files Browse the repository at this point in the history
  • Loading branch information
InsanusMokrassar committed Feb 19, 2025
1 parent b589142 commit de72843
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

* `Versions`:
* `SQLite`: `3.49.0.0` -> `3.49.1.0`
* `Common`:
* Add `retryOnFailure` utility for simple retries code writing
* `Repos`:
* `Cache`:
* Fix of `FullKeyValueCacheRepo` fields usage
Expand Down
26 changes: 26 additions & 0 deletions common/src/commonMain/kotlin/dev/inmo/micro_utils/common/Retry.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package dev.inmo.micro_utils.common

/**
* Will try to execute [action] and, if any exception will happen, execution will be retried.
* This process will happen at most [count] times. There is no any limits on [count] value, but [action] will run at
* least once and [retryOnFailure] will return its result if it is successful
*/
inline fun <T> retryOnFailure(count: Int, action: () -> T): T {
var triesCount = 0
while (true) {
val result = runCatching {
action()
}.onFailure {
triesCount++

if (triesCount >= count) {
throw it
} else {
null
}
}

if (result.isSuccess) return result.getOrThrow()
}
error("Unreachable code: retry must throw latest exception if error happen or success value if not")
}

0 comments on commit de72843

Please sign in to comment.