Created
September 3, 2024 23:43
-
-
Save vprabhu/69d912d7dfb8751badd26dff1d8eba1a to your computer and use it in GitHub Desktop.
This file contains hidden or 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.flow.flow | |
| import kotlinx.coroutines.launch | |
| suspend fun main(): Unit = coroutineScope { | |
| launch { | |
| println("Collector 1 in ${Thread.currentThread().name}") | |
| simpleFlow().collect { value -> | |
| println("Collecting from Collector 1 -> $value") | |
| } | |
| } | |
| launch { | |
| println("Collector 2 in ${Thread.currentThread().name}") | |
| simpleFlow().collect { value -> | |
| println("Collecting from Collector 2 -> $value") | |
| } | |
| } | |
| } | |
| private fun simpleFlow() = flow { | |
| println("Emission in ${Thread.currentThread().name}") | |
| repeat(3){ | |
| kotlinx.coroutines.delay(250) | |
| println("Emitting $it") | |
| emit(it) | |
| } | |
| } | |
| /** | |
| * output | |
| * Collector 1 in DefaultDispatcher-worker-2 | |
| * Collector 2 in DefaultDispatcher-worker-1 | |
| * Emission in DefaultDispatcher-worker-2 | |
| * Emission in DefaultDispatcher-worker-1 | |
| * Emitting 0 | |
| * Emitting 0 | |
| * Collecting from Collector 1 -> 0 | |
| * Collecting from Collector 2 -> 0 | |
| * Emitting 1 | |
| * Emitting 1 | |
| * Collecting from Collector 2 -> 1 | |
| * Collecting from Collector 1 -> 1 | |
| * Emitting 2 | |
| * Emitting 2 | |
| * Collecting from Collector 2 -> 2 | |
| * Collecting from Collector 1 -> 2 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment