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 ## 0.12.14
* `Coroutines`:
* Rewrite `awaitFirstWithDeferred` onto `CompletableDeferred` instead of coroutines suspending
## 0.12.13 ## 0.12.13
* `Coroutines`: * `Coroutines`:

View File

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