Skip to content

Instantly share code, notes, and snippets.

@kevalpatel2106
Created July 19, 2021 07:46
Show Gist options
  • Save kevalpatel2106/fa6887a07bd87aa952bce14d70641755 to your computer and use it in GitHub Desktop.
Save kevalpatel2106/fa6887a07bd87aa952bce14d70641755 to your computer and use it in GitHub Desktop.
Channel collection demo
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
fun main() {
GlobalScope.launch {
val channel = Channel<String>(Channel.BUFFERED)
channel.send("ABC")
delay(50)
channel.send("DEF")
channel.receiveAsFlow().collectLatest { // Try replacing it with collect once
delay(100)
// collectLatest: Should Print last sent value: DEF
// collect: Should print both, ABC & DEF
println("Collected -> $it")
}
}
println("collectionDemo finished\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment