nikolaymetchev
07/26/2023, 12:48 PMsuspend fun main() {
println(shortCircuit(1))
delay(10000)
}
private suspend fun shortCircuit(correctResult: Int): Int? = coroutineScope {
val channel = Channel<Int?>()
val n = 100
val coroutines: List<Job> = List(n) {
launch {
try {
delay(1000 + (it * 1000).toLong())
} catch(e: CancellationException) {
println("cancelled $it")
throw e
}
if (it == correctResult) {
println("sending $it")
channel.send(it)
}
println("Done $it")
}
}
val otherJob = launch {
coroutines.forEach { it.join() }
println("sending null")
channel.send(null)
}
val receive = channel.receive()
otherJob.cancel()
coroutines.forEach { it.cancel() }
receive
}
Joffrey
07/26/2023, 12:56 PMkevin.cianfarini
07/26/2023, 1:04 PMselect
here.nikolaymetchev
07/26/2023, 1:18 PMDmitry Khalanskiy [JB]
07/26/2023, 2:04 PMnikolaymetchev
07/27/2023, 12:00 PMDmitry Khalanskiy [JB]
07/27/2023, 12:06 PMCoroutineScope
, launch all the coroutines in that scope, and then, once one of them finds a result, simply cancel the scope as it's no longer needed.nikolaymetchev
07/27/2023, 12:37 PMnikolaymetchev
07/27/2023, 12:39 PMDmitry Khalanskiy [JB]
07/27/2023, 12:41 PMval scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
repeat(100) {
scope.launch {
if (it == 7) {
println("The correct result is found")
process(it)
scope.cancel()
}
}
}
Dmitry Khalanskiy [JB]
07/27/2023, 12:46 PMval answers = Channel<Int?>()
coroutineScope {
repeat(100) {
launch {
if (it == 7) {
answers.send(it)
this@coroutineScope.cancel()
}
}
}
}
// we will only be here once all the children of the coroutine scope are finished
answers.tryReceive()
aarkling
07/27/2023, 9:08 PMaarkling
07/27/2023, 9:08 PMsuspend fun <R> race(vararg races: suspend () -> R): R {
return channelFlow {
for (race in races) {
launch { send(race()) }
}
}.first()
}
nikolaymetchev
07/31/2023, 11:53 AMlouiscad
07/31/2023, 12:06 PMawaitCancellation()
nikolaymetchev
07/31/2023, 12:07 PMnikolaymetchev
07/31/2023, 12:33 PMlouiscad
07/31/2023, 12:34 PMlouiscad
07/31/2023, 12:35 PMnikolaymetchev
07/31/2023, 12:36 PM