Channels

The Deferred class, which was touched upon in the Parallel executing section, can be used to compute a single value. If we need to deal with a sequence of values, we can use channels. The Channel class contains the send and receive methods, which can be used in the following way:

fun main(args: Array<String>) = runBlocking<Unit> {
val channel = Channel<Int>()
launch {
for (x in 1..50) channel.send(x * x)
}
repeat(50) {
delay(500)
println(channel.receive())
}
println("Done!")
}

Channels also allow us to transfer values from one coroutine to another safely in a multithreaded environment.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.253.31