From ced05a458606e1359e5aaeb096cd6fa2ae3e5473 Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Fri, 9 Dec 2022 12:14:24 +0600 Subject: [PATCH] improve default runCatchingSafely/safelyWithResult and add suspend variances of safe/unsafe SafeWrapper interface --- .../dev/inmo/micro_utils/coroutines/HandleSafely.kt | 11 +++++++++++ safe_wrapper/build.gradle | 10 ++++++++++ safe_wrapper/src/commonMain/kotlin/SafeWrapper.kt | 6 +++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/HandleSafely.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/HandleSafely.kt index bc662e79086..c8ab319ea48 100644 --- a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/HandleSafely.kt +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/HandleSafely.kt @@ -115,10 +115,21 @@ suspend inline fun runCatchingSafely( safely(onException, block) } +suspend inline fun T.runCatchingSafely( + noinline onException: ExceptionHandler = defaultSafelyExceptionHandler, + noinline block: suspend T.() -> R +): Result = runCatching { + safely(onException) { block() } +} + suspend inline fun safelyWithResult( noinline block: suspend CoroutineScope.() -> T ): Result = runCatchingSafely(defaultSafelyExceptionHandler, block) +suspend inline fun T.safelyWithResult( + noinline block: suspend T.() -> R +): Result = runCatchingSafely(defaultSafelyExceptionHandler, block) + /** * Use this handler in cases you wish to include handling of exceptions by [defaultSafelyWithoutExceptionHandler] and * returning null at one time diff --git a/safe_wrapper/build.gradle b/safe_wrapper/build.gradle index 7c54502f100..854f51c5dfb 100644 --- a/safe_wrapper/build.gradle +++ b/safe_wrapper/build.gradle @@ -5,3 +5,13 @@ plugins { } apply from: "$mppProjectWithSerializationPresetPath" + +kotlin { + sourceSets { + commonMain { + dependencies { + api project(":micro_utils.coroutines") + } + } + } +} diff --git a/safe_wrapper/src/commonMain/kotlin/SafeWrapper.kt b/safe_wrapper/src/commonMain/kotlin/SafeWrapper.kt index f6e911189d5..6426ba6703e 100644 --- a/safe_wrapper/src/commonMain/kotlin/SafeWrapper.kt +++ b/safe_wrapper/src/commonMain/kotlin/SafeWrapper.kt @@ -1,8 +1,12 @@ package dev.inmo.micro_utils.safe_wrapper +import dev.inmo.micro_utils.coroutines.runCatchingSafely + interface SafeWrapper { - fun safe (block: T.() -> R): Result = unsafeTarget().runCatching(block) + fun safe(block: T.() -> R): Result = unsafeTarget().runCatching(block) fun unsafe(block: T.() -> R): R = unsafeTarget().block() + suspend fun safeS(block: suspend T.() -> R): Result = unsafeTarget().runCatchingSafely(block = block) + suspend fun unsafeS(block: suspend T.() -> R): R = unsafeTarget().block() fun unsafeTarget(): T class Default(private val t: T) : SafeWrapper { override fun unsafeTarget(): T = t }