https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

vide

03/14/2024, 9:29 AM
Is there any way to be sure that a value in a flow has been collected by all collectors? 🧵
Copy code
val flow = MutableStateFlow(0)
val testScope = TestScope()
val defaultScope = CoroutineScope(Dispatchers.Default)
val values = mutableListOf<Int>()
testScope.launch { flow.collect { values.add(it) } }
repeat(1000) { n ->
    defaultScope.launch { flow.value = n }
    runBlocking { flow.first { it == n } }
    testScope.testScheduler.runCurrent()
    assertEquals(values[n], n)
}
I would like to make sure that the collector running in testScope has collected before the assertion. I could wrap it in a loop that calls
runCurrent()
until it's done but I'm wondering if there's any other way.
The stuff happening in
defaultScope
is not really part of the test, it is some external code listening for updates on a websocket connection. The test actually works like:
Copy code
// mock update to websocket
flow.first { it == n }
testedScheduler.runCurrent()
// assert ui has updated
2 Views