Brendan Campbell-hartzell
03/28/2022, 2:10 AMrunTest
doesn't seem to wait for a collector running in another scope to fully process the emitted value before returning. Keeping everything in the runTest scope and context just hangs the test because Flow.collect on a sharedflow never returns.Trevor Stone
03/28/2022, 2:30 AMBrendan Campbell-hartzell
03/28/2022, 2:42 AM@Test
fun `does this even work`() {
val emitter = MutableSharedFlow<String>()
var emitted: String? = null
runTest {
val job = launch {
emitter.collect { emitted = it }
}
emitter.emit("new value")
job.cancel()
}
assertEquals("new value", emitted)
}
But this test failed.
Upon further investigation, replacing runTest
with runTest(UnconfinedTestDispatcher())
(to get similar behavior as runBlockingTest
) is what made it pass. Fingers crossed this remains consistent.Trevor Stone
03/28/2022, 2:54 AMBrendan Campbell-hartzell
03/28/2022, 4:40 PMrunTest
on its own, but the UnconfinedTestDispatcher
"eagerly enters all launch calls," so it actually behaves as I'd like it to.Trevor Stone
03/28/2022, 4:51 PMlaunch(start = CoroutineStart.UNDISPATCHED)
could also work more how you’re expectingBrendan Campbell-hartzell
03/28/2022, 4:58 PMlaunch
call is happing in production code, so I'm getting it to pass by providing the production code with a coroutine scope that will behave the way I need 🙂