import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
fun main() = runBlocking {
val fast = Channel<String>()
val slow = Channel<String>()
launch { delay(100); fast.send("fast") }
launch { delay(500); slow.send("slow") }
// Wait for whichever channel responds first
val first = select<String> {
fast.onReceive { it }
slow.onReceive { it }
}
println("got: $first") // fast
// With timeout — return null if neither responds in time
val maybe = withTimeoutOrNull(50) {
select<String> {
fast.onReceive { it }
slow.onReceive { it }
}
}
println("maybe: $maybe") // null (already consumed)
}
Create a free account and build your private vault. Share publicly whenever you want.