Lukasz Kalnik
04/13/2022, 2:24 PMcancelAllChildren of a runTest scope?
I have a test where I inject the test coroutineContext into a ViewModel and I want to cancel all running jobs inside the ViewModel when the test ends.Lukasz Kalnik
04/13/2022, 2:25 PMclass MyViewModel(coroutineContext: CoroutineContext = Dispatchers.Default) : ViewModel() {
private val coroutineScope = viewModelScope + coroutineContext
init {
coroutineScope.launch { myFlow.collect { /* do something with collected items */ } }
}
}
class MyViewModelTest {
@Test
fun testInitMyViewModel() = runTest {
MyViewModel(coroutineContext) // coroutineContext from test injected here
// test hangs and times out eventually because myFlow collection is not canceled
}
}Trevor Stone
04/13/2022, 2:28 PMval job = Job()
val coroutineContext: CoroutineContext = coroutineContext + job
job.cancel()
might workLukasz Kalnik
04/13/2022, 2:30 PMLukasz Kalnik
04/13/2022, 2:30 PMLukasz Kalnik
04/13/2022, 2:31 PMcoroutineContext already have a Job which I could reuse?Paul Woitaschek
04/13/2022, 2:53 PMLukasz Kalnik
04/13/2022, 2:58 PMPaul Woitaschek
04/13/2022, 3:00 PMPaul Woitaschek
04/13/2022, 3:01 PMLukasz Kalnik
04/13/2022, 3:04 PMLukasz Kalnik
04/13/2022, 3:04 PMcoroutineContext[Job] key!Lukasz Kalnik
04/13/2022, 3:04 PMPaul Woitaschek
04/13/2022, 3:05 PMLukasz Kalnik
04/13/2022, 3:38 PMcoroutineContext[Job]?.cancelChildren()