Update ActionWrapper.kt

This commit is contained in:
InsanusMokrassar 2023-01-31 00:11:45 +06:00 committed by GitHub
parent 79f2041565
commit 2645ea29d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,9 +3,23 @@ package dev.inmo.micro_utils.repos.cache.fallback
import dev.inmo.micro_utils.coroutines.runCatchingSafely import dev.inmo.micro_utils.coroutines.runCatchingSafely
import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeout
/**
* Realizations should [wrap] the work with some conditions like retries on exceptions, calling timeout, etc.
*
* @see Timeouted
* @see Direct
*/
interface ActionWrapper { interface ActionWrapper {
/**
* Should execute [block] to take the result [T], but may return failure in case when something went wrong.
* This method should never throw any [Exception]
*/
suspend fun <T> wrap(block: suspend () -> T): Result<T> suspend fun <T> wrap(block: suspend () -> T): Result<T>
/**
* This type of [ActionWrapper]s will use [withTimeout]([timeoutMillis]) and if original call
* will not return anything in that timeout just return [Result] with failure
*/
class Timeouted(private val timeoutMillis: Long) : ActionWrapper { class Timeouted(private val timeoutMillis: Long) : ActionWrapper {
override suspend fun <T> wrap(block: suspend () -> T): Result<T> = runCatchingSafely { override suspend fun <T> wrap(block: suspend () -> T): Result<T> = runCatchingSafely {
withTimeout(timeoutMillis) { withTimeout(timeoutMillis) {
@ -13,7 +27,11 @@ interface ActionWrapper {
} }
} }
} }
/**
* It is passthrough variant of [ActionWrapper] which will just call incoming block with wrapping into [runCatchingSafely]
*/
object Direct : ActionWrapper { object Direct : ActionWrapper {
override suspend fun <T> wrap(block: suspend () -> T): Result<T> = runCatchingSafely { block() } override suspend fun <T> wrap(block: suspend () -> T): Result<T> = runCatchingSafely { block() }
} }
} }