Last active
April 30, 2020 06:29
-
-
Save Moes81/9004bced45cf8ac986941f1184af91be to your computer and use it in GitHub Desktop.
Coroutine Channel playground for scratch file
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
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.channels.Channel | |
import kotlinx.coroutines.channels.consumeEach | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.launch | |
import kotlinx.coroutines.runBlocking | |
runBlocking { | |
val sendChannel = Channel<Int>(4) | |
println("Starting") | |
val job1 = launch(Dispatchers.IO) { | |
println("producer: In producer coroutine") | |
for (i in 0..10) { | |
println("producer: offering $i") | |
val offerResult = sendChannel.offer(i) | |
if (!offerResult) { | |
println("producer: Channel buffer is full. Dropping data $i") | |
} | |
// val offerResult = sendChannel.send(i) | |
println("producer: offer result: $offerResult") | |
delay(100) | |
} | |
sendChannel.close() | |
} | |
val job2 = launch(Dispatchers.IO) { | |
println("consumer: In consumer coroutine") | |
val delayToConsume = 600L | |
delay(delayToConsume) | |
println("consumer: start consuming after $delayToConsume ms") | |
for (msg in sendChannel){ | |
println("consumer: consuming $msg") | |
} | |
} | |
job1.join() | |
job2.join() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment