Skip to content

Instantly share code, notes, and snippets.

@CodyEngel
Created December 4, 2018 21:16
Show Gist options
  • Save CodyEngel/29c52c19f5c3b3265953f517fb6c0dc3 to your computer and use it in GitHub Desktop.
Save CodyEngel/29c52c19f5c3b3265953f517fb6c0dc3 to your computer and use it in GitHub Desktop.
This is an example of the different channel types with coroutines and some scenarios. Note that sendBlockingBeforeReceiverScenario will cause the program to stop executing, DON'T USE SENDBLOCKING!
import kotlinx.coroutines.experimental.GlobalScope
import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.Channel.Factory.CONFLATED
import kotlinx.coroutines.experimental.channels.Channel.Factory.UNLIMITED
import kotlinx.coroutines.experimental.channels.sendBlocking
import kotlinx.coroutines.experimental.launch
fun main(args: Array<String>) {
val channels = listOf<Channel<Int>>(
Channel(capacity = UNLIMITED),
Channel(capacity = CONFLATED),
Channel(capacity = 12),
Channel()
)
channels.forEach { channel ->
sendAndReceiveAsyncScenario(channel)
sendBlockingAfterReceiverScenario(channel)
sendBlockingBeforeReceiverScenario(channel)
}
}
private fun sendBlockingBeforeReceiverScenario(channel: Channel<Int>) {
println("sendBlockingBeforeReceiverScenario: ${channel.javaClass}")
println("Sending Value...")
channel.sendBlocking(1)
println("Waiting For Value...")
GlobalScope.launch {
val whatAreYou = channel.receive()
println("Received Value: $whatAreYou")
}
Thread.sleep(25)
}
private fun sendBlockingAfterReceiverScenario(channel: Channel<Int>) {
println("sendBlockingAfterReceiverScenario: ${channel.javaClass}")
println("Sending Value...")
GlobalScope.launch {
val whatAreYou = channel.receive()
println("Received Value: $whatAreYou")
}
channel.sendBlocking(1)
println("Waiting For Value...")
Thread.sleep(25)
}
private fun sendAndReceiveAsyncScenario(channel: Channel<Int>) {
println("sendAndReceiveAsyncScenario: ${channel.javaClass}")
println("Sending Value...")
GlobalScope.launch {
channel.send(1)
}
println("Waiting For Value...")
GlobalScope.launch {
val whatAreYou = channel.receive()
println("Received Value: $whatAreYou")
}
Thread.sleep(25)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment