Skip to content

Instantly share code, notes, and snippets.

@vprabhu
Created September 3, 2024 23:44
Show Gist options
  • Save vprabhu/30f210ce4f9e8a3b89b2b92416e53493 to your computer and use it in GitHub Desktop.
Save vprabhu/30f210ce4f9e8a3b89b2b92416e53493 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
suspend fun main(): Unit = coroutineScope {
val sharedFlow = MutableSharedFlow<Int>()
launch {
println("Emitting in ${Thread.currentThread().name}")
repeat(3) {
kotlinx.coroutines.delay(250)
println("Emitting $it")
sharedFlow.emit(it)
}
}
launch {
println("Collector 1 in ${Thread.currentThread().name}")
delay(550)
sharedFlow.collect { value ->
println("Collecting from Collector 1 -> $value")
}
}
launch {
println("Collector 2 in ${Thread.currentThread().name}")
sharedFlow.collect { value ->
println("Collecting from Collector 2 -> $value")
}
}
}
/**
* output :
* Emitting in DefaultDispatcher-worker-2
* Collector 1 in DefaultDispatcher-worker-1
* Collector 2 in DefaultDispatcher-worker-3
* Emitting 0
* Collecting from Collector 2 -> 0
* Emitting 1
* Collecting from Collector 2 -> 1
* Emitting 2
* Collecting from Collector 1 -> 2
* Collecting from Collector 2 -> 2
*
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment