mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-12-18 14:47:15 +00:00
improvements in AwaitFirst
This commit is contained in:
parent
a10d2184ff
commit
1642f7abd9
@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
## 0.12.14
|
## 0.12.14
|
||||||
|
|
||||||
|
* `Coroutines`:
|
||||||
|
* Rewrite `awaitFirstWithDeferred` onto `CompletableDeferred` instead of coroutines suspending
|
||||||
|
|
||||||
## 0.12.13
|
## 0.12.13
|
||||||
|
|
||||||
* `Coroutines`:
|
* `Coroutines`:
|
||||||
|
@ -6,23 +6,19 @@ import kotlin.coroutines.*
|
|||||||
suspend fun <T> Iterable<Deferred<T>>.awaitFirstWithDeferred(
|
suspend fun <T> Iterable<Deferred<T>>.awaitFirstWithDeferred(
|
||||||
scope: CoroutineScope,
|
scope: CoroutineScope,
|
||||||
cancelOnResult: Boolean = true
|
cancelOnResult: Boolean = true
|
||||||
): Pair<Deferred<T>, T> = suspendCoroutine<Pair<Deferred<T>, T>> { continuation ->
|
): Pair<Deferred<T>, T> {
|
||||||
scope.launch(SupervisorJob()) {
|
val resultDeferred = CompletableDeferred<Pair<Deferred<T>, T>>()
|
||||||
val scope = this
|
val scope = scope.LinkedSupervisorScope()
|
||||||
forEach {
|
forEach {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
continuation.resume(it to it.await())
|
resultDeferred.complete(it to it.await())
|
||||||
scope.cancel()
|
scope.cancel()
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}.also {
|
return resultDeferred.await().also {
|
||||||
if (cancelOnResult) {
|
if (cancelOnResult) {
|
||||||
forEach {
|
forEach {
|
||||||
try {
|
runCatchingSafely { it.cancel() }
|
||||||
it.cancel()
|
|
||||||
} catch (e: IllegalStateException) {
|
|
||||||
e.printStackTrace()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user