Kotlin

select — Choose Among Channels

admin by @admin ADMIN
Jun 16, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`select { }` lets a coroutine wait on multiple suspending operations and proceed when the first one is ready — like nginx select() but for channels, deferreds, and timers.
Kotlin
Raw
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)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.