Last active
April 30, 2020 06:32
-
-
Save Moes81/b171ee5ac36c9bfcc55d5c95c47653a8 to your computer and use it in GitHub Desktop.
coroutine BroadcastChannel 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.* | |
import kotlinx.coroutines.channels.BroadcastChannel | |
import kotlinx.coroutines.channels.Channel | |
import kotlinx.coroutines.channels.consumeEach | |
runBlocking { | |
val sendChannel = BroadcastChannel<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 1: In consumer coroutine") | |
val delayToConsume = 400L | |
delay(delayToConsume) | |
println("consumer 1: start consuming after $delayToConsume ms") | |
for (msg in sendChannel.openSubscription()){ | |
println("consumer 1: consuming $msg") | |
} | |
} | |
val job3 = launch(Dispatchers.IO) { | |
println("consumer 2: In consumer coroutine") | |
val delayToConsume = 300L | |
delay(delayToConsume) | |
val duration = 300L | |
withTimeout(duration){ | |
println("consumer 2: start consuming after $delayToConsume ms for duration of $duration ms") | |
for (msg in sendChannel.openSubscription()){ | |
println("consumer 2: consuming $msg") | |
} | |
} | |
} | |
job1.join() | |
job2.join() | |
job3.join() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment