diff --git a/CHANGELOG.md b/CHANGELOG.md index e38002534f4..37576b03f1c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 0.12.14 +* `Coroutines`: + * Rewrite `awaitFirstWithDeferred` onto `CompletableDeferred` instead of coroutines suspending + ## 0.12.13 * `Coroutines`: diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/AwaitFirst.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/AwaitFirst.kt index 4c096027fd9..6f85dac8004 100644 --- a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/AwaitFirst.kt +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/AwaitFirst.kt @@ -6,23 +6,19 @@ import kotlin.coroutines.* suspend fun Iterable>.awaitFirstWithDeferred( scope: CoroutineScope, cancelOnResult: Boolean = true -): Pair, T> = suspendCoroutine, T>> { continuation -> - scope.launch(SupervisorJob()) { - val scope = this - forEach { - scope.launch { - continuation.resume(it to it.await()) - scope.cancel() - } +): Pair, T> { + val resultDeferred = CompletableDeferred, T>>() + val scope = scope.LinkedSupervisorScope() + forEach { + scope.launch { + resultDeferred.complete(it to it.await()) + scope.cancel() } } -}.also { - if (cancelOnResult) { - forEach { - try { - it.cancel() - } catch (e: IllegalStateException) { - e.printStackTrace() + return resultDeferred.await().also { + if (cancelOnResult) { + forEach { + runCatchingSafely { it.cancel() } } } }