Last active
January 12, 2020 20:34
-
-
Save juliuscanute/5450184749b593ea43998cec3fd7e817 to your computer and use it in GitHub Desktop.
[Poll vs Receive] #poll #coroutine #kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Received: Apple | |
Sent: Apple | |
Received: Banana | |
Sent: Banana | |
Channel is empty | |
Channel is empty | |
Channel is empty | |
Done! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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