mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-12-23 00:57:15 +00:00
add Synchronously
This commit is contained in:
parent
2d5304a770
commit
f3bec34882
@ -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`
|
||||
|
@ -0,0 +1,28 @@
|
||||
package dev.inmo.micro_utils.coroutines
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
|
||||
fun <T> 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!!
|
||||
}
|
@ -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 })
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user