Channels in Kotlin
In Kotlin, we can use coroutines and channels to achieve similar functionality to Go’s goroutines and channels. Channels in Kotlin are a way to transfer a stream of values between coroutines.
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
// Create a new channel with Channel<String>()
// Channels are typed by the values they convey
val messages = Channel<String>()
// Launch a new coroutine to send a value into the channel
// using the channel.send() method
launch {
messages.send("ping")
}
// Receive a value from the channel using channel.receive()
// Here we'll receive the "ping" message we sent above and print it out
val msg = messages.receive()
println(msg)
// Close the channel when it's no longer needed
messages.close()
}
When we run the program, the “ping” message is successfully passed from one coroutine to another via our channel.
$ kotlinc -cp kotlinx-coroutines-core.jar channels.kt -include-runtime -d channels.jar
$ java -jar channels.jar
ping
By default, send
is a suspending function and receive
blocks until a value is available. This property allowed us to wait at the end of our program for the “ping” message without having to use any other synchronization.
In Kotlin, channels are hot streams, which means they start producing values as soon as they’re created. They also provide backpressure, automatically suspending the sender when the channel is full.
Note that to use channels in Kotlin, you need to include the kotlinx-coroutines-core
library in your project dependencies.