mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-19 23:03:49 +00:00
rewrite launchSynchronously
This commit is contained in:
parent
7f813a519b
commit
9e02c3e5ff
@ -3,17 +3,16 @@ package dev.inmo.micro_utils.coroutines
|
|||||||
import kotlinx.coroutines.*
|
import kotlinx.coroutines.*
|
||||||
|
|
||||||
fun <T> CoroutineScope.launchSynchronously(block: suspend CoroutineScope.() -> T): T {
|
fun <T> CoroutineScope.launchSynchronously(block: suspend CoroutineScope.() -> T): T {
|
||||||
var throwable: Throwable? = null
|
val deferred = CompletableDeferred<T>()
|
||||||
var result: T? = null
|
|
||||||
val objectToSynchronize = java.lang.Object()
|
val objectToSynchronize = java.lang.Object()
|
||||||
val launchCallback = {
|
val launchCallback = {
|
||||||
launch {
|
launch {
|
||||||
safely(
|
safely(
|
||||||
{
|
{
|
||||||
throwable = it
|
deferred.completeExceptionally(it)
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
result = block()
|
deferred.complete(block())
|
||||||
}
|
}
|
||||||
synchronized(objectToSynchronize) {
|
synchronized(objectToSynchronize) {
|
||||||
objectToSynchronize.notifyAll()
|
objectToSynchronize.notifyAll()
|
||||||
@ -24,7 +23,7 @@ fun <T> CoroutineScope.launchSynchronously(block: suspend CoroutineScope.() -> T
|
|||||||
launchCallback()
|
launchCallback()
|
||||||
objectToSynchronize.wait()
|
objectToSynchronize.wait()
|
||||||
}
|
}
|
||||||
throw throwable ?: return result!!
|
return deferred.getCompleted()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun <T> launchSynchronously(block: suspend CoroutineScope.() -> T): T = CoroutineScope(Dispatchers.Default).launchSynchronously(block)
|
fun <T> launchSynchronously(block: suspend CoroutineScope.() -> T): T = CoroutineScope(Dispatchers.Default).launchSynchronously(block)
|
||||||
|
Loading…
Reference in New Issue
Block a user