improvements in AwaitFirst

This commit is contained in:
InsanusMokrassar 2022-09-21 18:00:39 +06:00
parent a10d2184ff
commit 1642f7abd9
2 changed files with 14 additions and 15 deletions

View File

@ -2,6 +2,9 @@
## 0.12.14
* `Coroutines`:
* Rewrite `awaitFirstWithDeferred` onto `CompletableDeferred` instead of coroutines suspending
## 0.12.13
* `Coroutines`:

View File

@ -6,23 +6,19 @@ import kotlin.coroutines.*
suspend fun <T> Iterable<Deferred<T>>.awaitFirstWithDeferred(
scope: CoroutineScope,
cancelOnResult: Boolean = true
): Pair<Deferred<T>, T> = suspendCoroutine<Pair<Deferred<T>, T>> { continuation ->
scope.launch(SupervisorJob()) {
val scope = this
): Pair<Deferred<T>, T> {
val resultDeferred = CompletableDeferred<Pair<Deferred<T>, T>>()
val scope = scope.LinkedSupervisorScope()
forEach {
scope.launch {
continuation.resume(it to it.await())
resultDeferred.complete(it to it.await())
scope.cancel()
}
}
}
}.also {
return resultDeferred.await().also {
if (cancelOnResult) {
forEach {
try {
it.cancel()
} catch (e: IllegalStateException) {
e.printStackTrace()
runCatchingSafely { it.cancel() }
}
}
}