Merge pull request #27 from InsanusMokrassar/0.4.9

add Synchronously
This commit is contained in:
InsanusMokrassar 2020-12-02 17:29:27 +06:00 committed by GitHub
commit f2c1b3c76a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 43 additions and 0 deletions

View File

@ -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`

View File

@ -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!!
}

View File

@ -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 })
}
}
}