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

gmaciel

06/29/2020, 11:39 AM
I'm trying to run a test but keep getting
This job has not completed yet
, any ideas what i'm doing wrong here:
Copy code
@Test
fun test() = runBlockingTest {
    val mutableStateFlow = MutableStateFlow(0)
    mutableStateFlow.value = 1
    mutableStateFlow.value = 2

    val result = mutableListOf<Int>()

    mutableStateFlow.collect {
        result.add(it)
    }

    assertEquals(listOf(0, 1, 2), result)
}
d

Dominaezzz

06/29/2020, 11:58 AM
This test looks like it'll suspend forever. Do you have a stacktrace?
g

gildor

06/29/2020, 12:17 PM
Instead of collect you should use take(3).toList(), otherwise it will never complete as Dominic said, StateFlow never completes
g

gmaciel

06/29/2020, 12:20 PM
Oh ok, yeah that what's happening! Thanks!
d

Daniel

07/01/2020, 6:10 PM
why would it suspend forever @Dominaezzz
I’ve faced the same issue with testing retrofit suspend calls
d

Dominaezzz

07/01/2020, 6:23 PM
`StateFlow`s never complete. Since the value can change so long as the object exists.
d

Daniel

07/01/2020, 9:25 PM
Okay thanks
Why does calling take(3).toList() make the test pass
d

Dominaezzz

07/01/2020, 10:46 PM
take(3)
takes the first three emissions and then terminates collection.
2 Views