improve default runCatchingSafely/safelyWithResult and add suspend variances of safe/unsafe SafeWrapper interface

This commit is contained in:
InsanusMokrassar 2022-12-09 12:14:24 +06:00
parent 43fe06206a
commit ced05a4586
3 changed files with 26 additions and 1 deletions

View File

@ -115,10 +115,21 @@ suspend inline fun <T> runCatchingSafely(
safely(onException, block)
}
suspend inline fun <T, R> T.runCatchingSafely(
noinline onException: ExceptionHandler<R> = defaultSafelyExceptionHandler,
noinline block: suspend T.() -> R
): Result<R> = runCatching {
safely(onException) { block() }
}
suspend inline fun <T> safelyWithResult(
noinline block: suspend CoroutineScope.() -> T
): Result<T> = runCatchingSafely(defaultSafelyExceptionHandler, block)
suspend inline fun <T, R> T.safelyWithResult(
noinline block: suspend T.() -> R
): Result<R> = runCatchingSafely(defaultSafelyExceptionHandler, block)
/**
* Use this handler in cases you wish to include handling of exceptions by [defaultSafelyWithoutExceptionHandler] and
* returning null at one time

View File

@ -5,3 +5,13 @@ plugins {
}
apply from: "$mppProjectWithSerializationPresetPath"
kotlin {
sourceSets {
commonMain {
dependencies {
api project(":micro_utils.coroutines")
}
}
}
}

View File

@ -1,8 +1,12 @@
package dev.inmo.micro_utils.safe_wrapper
import dev.inmo.micro_utils.coroutines.runCatchingSafely
interface SafeWrapper<T> {
fun <R> safe (block: T.() -> R): Result<R> = unsafeTarget().runCatching(block)
fun <R> safe(block: T.() -> R): Result<R> = unsafeTarget().runCatching(block)
fun <R> unsafe(block: T.() -> R): R = unsafeTarget().block()
suspend fun <R> safeS(block: suspend T.() -> R): Result<R> = unsafeTarget().runCatchingSafely(block = block)
suspend fun <R> unsafeS(block: suspend T.() -> R): R = unsafeTarget().block()
fun unsafeTarget(): T
class Default<T>(private val t: T) : SafeWrapper<T> { override fun unsafeTarget(): T = t }