add Synchronously

This commit is contained in:
2020-12-02 17:28:59 +06:00
parent 2d5304a770
commit f3bec34882
3 changed files with 43 additions and 0 deletions

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