From f3bec34882389f78aae78775ba4f7169496b07ad Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Wed, 2 Dec 2020 17:28:59 +0600 Subject: [PATCH] add Synchronously --- CHANGELOG.md | 2 ++ .../coroutines/LaunchSynchronously.kt | 28 +++++++++++++++++++ .../coroutines/LaunchSynchronouslyTest.kt | 13 +++++++++ 3 files changed, 43 insertions(+) create mode 100644 coroutines/src/jvmMain/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronously.kt create mode 100644 coroutines/src/jvmTest/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronouslyTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 4763091a4a6..cf9d5eecd11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ * `Versions`: * `Ktor`: `1.4.2` -> `1.4.3` +* `Coroutines`: + * `launchSynchronously` has been added in JVM * `Repo` * `Common` * In repos different usages of `BroadcastChannel`s has been replaced with `MutableSharedFlow` 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 new file mode 100644 index 00000000000..c2a226e18be --- /dev/null +++ b/coroutines/src/jvmMain/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronously.kt @@ -0,0 +1,28 @@ +package dev.inmo.micro_utils.coroutines + +import kotlinx.coroutines.* + +fun launchSynchronously(scope: CoroutineScope = CoroutineScope(Dispatchers.Default), block: suspend CoroutineScope.() -> T): T { + var throwable: Throwable? = null + var result: T? = null + val objectToSynchronize = java.lang.Object() + val launchCallback = { + scope.launch { + safely( + { + throwable = it + } + ) { + result = block() + } + synchronized(objectToSynchronize) { + objectToSynchronize.notifyAll() + } + } + } + synchronized(objectToSynchronize) { + launchCallback() + objectToSynchronize.wait() + } + throw throwable ?: return result!! +} diff --git a/coroutines/src/jvmTest/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronouslyTest.kt b/coroutines/src/jvmTest/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronouslyTest.kt new file mode 100644 index 00000000000..9a9859057da --- /dev/null +++ b/coroutines/src/jvmTest/kotlin/dev/inmo/micro_utils/coroutines/LaunchSynchronouslyTest.kt @@ -0,0 +1,13 @@ +package dev.inmo.micro_utils.coroutines + +import kotlin.test.Test +import kotlin.test.assertEquals + +class LaunchSynchronouslyTest { + @Test + fun testRunInCoroutine() { + (0 .. 10000).forEach { + assertEquals(it, launchSynchronously { it }) + } + } +} \ No newline at end of file