Receiving from a Channel

With your producer in place, you can create your first worker. Add a function to define the worker’s behavior, then launch it in its own coroutine.

Listing 22.2  Receiving from a channel (FlightWatcher.kt)

...
suspend fun fetchFlights(
    passengerNames: List<String> = listOf("Madrigal", "Polarcubis")
): List<FlightStatus> = coroutineScope {
    val passengerNamesChannel = Channel<String>()

    launch {
        passengerNames.forEach {
            passengerNamesChannel.send(it)
        }
    }

    launch {
        fetchFlightStatuses(passengerNamesChannel)
    }

    emptyList()
}

suspend fun fetchFlightStatuses(
    fetchChannel: Channel<String>
) {
    val passengerName = fetchChannel.receive()
    val flight = fetchFlight(passengerName)
    println("Fetched flight: $flight")
}

Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.