Skip to content

Instantly share code, notes, and snippets.

@juliuscanute
Last active January 12, 2020 20:34
Show Gist options
  • Save juliuscanute/5450184749b593ea43998cec3fd7e817 to your computer and use it in GitHub Desktop.
Save juliuscanute/5450184749b593ea43998cec3fd7e817 to your computer and use it in GitHub Desktop.
[Poll vs Receive] #poll #coroutine #kotlin
Received: Apple
Sent: Apple
Received: Banana
Sent: Banana
Channel is empty
Channel is empty
Channel is empty
Done!
fun main() {
val fruitArray = arrayOf("Apple", "Banana", "Pear", "Grapes", "Strawberry")
val kotlinChannel = Channel<String>()
runBlocking {
launch {
for (fruit in fruitArray) {
if (fruit == "Pear") {
break
}
kotlinChannel.send(fruit)
println("Sent: $fruit")
}
}
launch {
repeat(fruitArray.size) {
val fruit = kotlinChannel.poll()
if (fruit != null) {
println("Received: $fruit")
} else {
println("Channel is empty")
}
delay(500)
}
println("Done!")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment