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.class 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 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 PMLukasz Kalnik
04/13/2022, 3:04 PMcoroutineContext[Job]
key!Paul Woitaschek
04/13/2022, 3:05 PMLukasz Kalnik
04/13/2022, 3:38 PMcoroutineContext[Job]?.cancelChildren()