mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2025-09-08 17:49:44 +00:00
Retry
This commit is contained in:
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
* `Versions`:
|
* `Versions`:
|
||||||
* `SQLite`: `3.49.0.0` -> `3.49.1.0`
|
* `SQLite`: `3.49.0.0` -> `3.49.1.0`
|
||||||
|
* `Common`:
|
||||||
|
* Add `retryOnFailure` utility for simple retries code writing
|
||||||
* `Repos`:
|
* `Repos`:
|
||||||
* `Cache`:
|
* `Cache`:
|
||||||
* Fix of `FullKeyValueCacheRepo` fields usage
|
* Fix of `FullKeyValueCacheRepo` fields usage
|
||||||
|
@@ -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")
|
||||||
|
}
|
Reference in New Issue
Block a user