Skip to content

Instantly share code, notes, and snippets.

@mo0rti
Created May 19, 2023 10:16
Show Gist options
  • Save mo0rti/aaf7f3d58e0024ff993bb59aecc6ba38 to your computer and use it in GitHub Desktop.
Save mo0rti/aaf7f3d58e0024ff993bb59aecc6ba38 to your computer and use it in GitHub Desktop.
fun rendezvousChannel(
coroutineScope: CoroutineScope
) {
// create a rendezvous channel with capacity 0
val channel = Channel<Int>()
// get the starting time to display the time difference in the logs
val startTime = System.currentTimeMillis()
// launch the producer coroutine
coroutineScope.launch {
for (i in 1..5) {
log( "Producer -> Sending $i", startTime)
channel.send(i) // send data to the channel
log( "Producer -> Sent $i", startTime)
}
channel.close() // close the channel after sending all data
}
// launch the consumer coroutine
coroutineScope.launch {
// iterate over the channel until it's closed
for (value in channel) {
log("Consumer Received $value", startTime)
}
}
}
// To log the message and time
fun log(message: String, startTime: Long) {
val currentTime = System.currentTimeMillis()
val diffTime = String.format("%.3f", (currentTime - startTime).toDouble() / 1000)
Log.d(TAG,"[$diffTime] $message")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment