Skip to content

Instantly share code, notes, and snippets.

@Moes81
Last active April 30, 2020 06:29
Show Gist options
  • Save Moes81/9004bced45cf8ac986941f1184af91be to your computer and use it in GitHub Desktop.
Save Moes81/9004bced45cf8ac986941f1184af91be to your computer and use it in GitHub Desktop.
Coroutine Channel playground for scratch file
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