Created
September 3, 2024 23:44
-
-
Save vprabhu/30f210ce4f9e8a3b89b2b92416e53493 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
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