October 2021
Intermediate to advanced
500 pages
16h 23m
English
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")
}Read now
Unlock full access