Created
May 19, 2023 10:16
-
-
Save mo0rti/aaf7f3d58e0024ff993bb59aecc6ba38 to your computer and use it in GitHub Desktop.
This file contains 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 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