import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val ch = Channel<Int>(capacity = 10)
// Producer
launch {
for (i in 1..5) {
ch.send(i)
println("produced $i")
}
ch.close() // signal "no more" to consumer
}
// Consumer — `for` over a channel terminates when closed
launch {
for (item in ch) {
println("consumed $item")
delay(50)
}
println("channel closed")
}
}
Create a free account and build your private vault. Share publicly whenever you want.