mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-26 03:58:45 +00:00
improve launchSynchronously
This commit is contained in:
parent
1f466747f0
commit
623e0cd369
@ -4,6 +4,9 @@
|
|||||||
|
|
||||||
* `Versions`
|
* `Versions`
|
||||||
* `Exposed`: `0.31.1` -> `0.32.1`
|
* `Exposed`: `0.31.1` -> `0.32.1`
|
||||||
|
* `Coroutines`
|
||||||
|
* `JVM`
|
||||||
|
* `launchSynchronously` and subsequent functions got improved mechanism
|
||||||
|
|
||||||
## 0.5.5
|
## 0.5.5
|
||||||
|
|
||||||
|
@ -115,6 +115,12 @@ suspend inline fun <T> runCatchingSafely(
|
|||||||
safely(onException, block)
|
safely(onException, block)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend inline fun <T> safelyWithResult(
|
||||||
|
noinline block: suspend CoroutineScope.() -> T
|
||||||
|
): Result<T> = runCatching {
|
||||||
|
safely({ throw it }, block)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Use this handler in cases you wish to include handling of exceptions by [defaultSafelyWithoutExceptionHandler] and
|
* Use this handler in cases you wish to include handling of exceptions by [defaultSafelyWithoutExceptionHandler] and
|
||||||
* returning null at one time
|
* returning null at one time
|
||||||
|
@ -3,27 +3,21 @@ 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 {
|
||||||
val deferred = CompletableDeferred<T>()
|
var result: Result<T>? = null
|
||||||
val objectToSynchronize = java.lang.Object()
|
val objectToSynchronize = Object()
|
||||||
val launchCallback = {
|
synchronized(objectToSynchronize) {
|
||||||
launch {
|
launch {
|
||||||
safely(
|
result = safelyWithResult(block)
|
||||||
{
|
}.invokeOnCompletion {
|
||||||
deferred.completeExceptionally(it)
|
|
||||||
}
|
|
||||||
) {
|
|
||||||
deferred.complete(block())
|
|
||||||
}
|
|
||||||
synchronized(objectToSynchronize) {
|
synchronized(objectToSynchronize) {
|
||||||
objectToSynchronize.notifyAll()
|
objectToSynchronize.notifyAll()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
while (result == null) {
|
||||||
synchronized(objectToSynchronize) {
|
|
||||||
launchCallback()
|
|
||||||
objectToSynchronize.wait()
|
objectToSynchronize.wait()
|
||||||
}
|
}
|
||||||
return deferred.getCompleted()
|
}
|
||||||
|
return result!!.getOrThrow()
|
||||||
}
|
}
|
||||||
|
|
||||||
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