Андрей Коровин
09/01/2021, 6:29 PMjava.lang.IllegalStateException: This job has not completed yet
@Test
fun testHotFlow() = coroutinesTestRule.testDispatcher.runBlockingTest {
val eventChannel = Channel<String>()
val events = eventChannel.receiveAsFlow()
val event = events.first()
assertEquals(event, null)
}
2. This test doesn’t fail
@Test
fun testHotFlow() = coroutinesTestRule.testDispatcher.runBlockingTest {
val eventChannel = Channel<String>()
val events = eventChannel.receiveAsFlow()
launch {
eventChannel.send("First element")
}
val event = events.first()
assertNotNull(event)
}
ephemient
09/01/2021, 6:42 PM.firstOrNull()
?Андрей Коровин
09/01/2021, 7:05 PMephemient
09/01/2021, 7:20 PM.first()
is wrong even if it worked, because it won't return null.firstOrNull()
is only broken because it needs the flow to either emit or terminate (which is also wrong with .first()
)Андрей Коровин
09/02/2021, 8:32 AMit needs the flow to either emit or terminateBut why does it fail with “java.lang.IllegalStateException: This job has not completed yet” in the first example. And why it doesn’t fail after it emits something (
eventChannel.send("First element")
)? Isn’t the job still running?ephemient
09/02/2021, 8:45 AM.shareIn(this)
then the second test wouldn't pass because that launches a coroutine that will keep runningАндрей Коровин
09/02/2021, 8:53 AMzero runnable childrenMeaning that nothing can send/terminate the flow?
so everything can wrap upbut isn’t the flow still running? Or it is the
first()
function that creates the job that “has not completed yet”a coroutine that will keep running
@Test
fun testHotFlow() = coroutinesTestRule.testDispatcher.runBlockingTest {
val eventChannel = Channel<String>()
val events = eventChannel.receiveAsFlow().shareIn(this, SharingStarted.Lazily)
launch {
eventChannel.send("First element")
}
val event = events.first()
assertNotNull(event)
}
you are right, it fails, but with more meaningful message:
Test finished with active jobs: ["coroutine#2":StandaloneCoroutine{Active}@244e30dd]
kotlinx.coroutines.test.UncompletedCoroutinesError: Test finished with active jobs: ["coroutine#2":StandaloneCoroutine{Active}@244e30dd]
ephemient
09/02/2021, 8:56 AMАндрей Коровин
09/02/2021, 9:05 AMephemient
09/02/2021, 9:07 AMАндрей Коровин
09/02/2021, 9:07 AMyou don’t know that is emptyso it’s wrong to assume that it’s empty in the first place