Carrascado
08/26/2020, 6:42 PMThe pattern where a coroutine is producing a sequence of elements is quite common. This is a part of producer-consumer pattern that is often found in concurrent code. You could abstract such a producer into a function that takes channel as its parameter, but this goes contrary to common sense that results must be returned from functions.It means something like this?
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
suspend fun produceSquares(channel: Channel<Int>) {
for (x in 1..5) channel.send(x * x)
channel.close()
}
fun main() = runBlocking {
val squares: Channel<Int> = Channel()
launch {
produceSquares(squares)
}
for (value in squares) {
println(value)
}
println("Done!")
}