package dev.inmo.micro_utils.coroutines import kotlinx.coroutines.* import kotlin.coroutines.* suspend fun Iterable>.awaitFirstWithDeferred( scope: CoroutineScope, cancelOnResult: Boolean = true ): Pair, T> { val resultDeferred = CompletableDeferred, T>>() val scope = scope.LinkedSupervisorScope() forEach { scope.launch { resultDeferred.complete(it to it.await()) scope.cancel() } } return resultDeferred.await().also { if (cancelOnResult) { forEach { runCatchingSafely { it.cancel() } } } } } suspend fun Iterable>.awaitFirst( scope: CoroutineScope, cancelOnResult: Boolean = true ): T = awaitFirstWithDeferred(scope, cancelOnResult).second suspend fun Iterable>.awaitFirst( cancelOthers: Boolean = true ): T = awaitFirst(CoroutineScope(coroutineContext), cancelOthers)