From 9e02c3e5ff2121b7d91bec2ddd878e4b6a15df0c Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Tue, 20 Apr 2021 21:39:21 +0600 Subject: [PATCH] rewrite launchSynchronously --- .../inmo/micro_utils/coroutines/LaunchSynchronously.kt | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/coroutines/src/jvmMain/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronously.kt b/coroutines/src/jvmMain/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronously.kt index bfd044534b5..36e7d8b608a 100644 --- a/coroutines/src/jvmMain/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronously.kt +++ b/coroutines/src/jvmMain/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronously.kt @@ -3,17 +3,16 @@ package dev.inmo.micro_utils.coroutines import kotlinx.coroutines.* fun CoroutineScope.launchSynchronously(block: suspend CoroutineScope.() -> T): T { - var throwable: Throwable? = null - var result: T? = null + val deferred = CompletableDeferred() val objectToSynchronize = java.lang.Object() val launchCallback = { launch { safely( { - throwable = it + deferred.completeExceptionally(it) } ) { - result = block() + deferred.complete(block()) } synchronized(objectToSynchronize) { objectToSynchronize.notifyAll() @@ -24,7 +23,7 @@ fun CoroutineScope.launchSynchronously(block: suspend CoroutineScope.() -> T launchCallback() objectToSynchronize.wait() } - throw throwable ?: return result!! + return deferred.getCompleted() } fun launchSynchronously(block: suspend CoroutineScope.() -> T): T = CoroutineScope(Dispatchers.Default).launchSynchronously(block)