Is there a way to `cancelAllChildren` of a `runTes...
# coroutines
l
Is there a way to
cancelAllChildren
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.
Copy code
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
    }
}
t
Copy code
val job = Job()
val coroutineContext: CoroutineContext = coroutineContext + job

job.cancel()
might work
l
Yup, works perfectly! Thanks for a quick and helpful answer.
If only it could be somehow automatized...
Doesn't
coroutineContext
already have a
Job
which I could reuse?
p
You can call into the children
l
How?
p
Sth like coroutineContext[Job].children().forEach it cancel
Coding on my phone ;-)
l
Thanks, that works!
The part I was missing was the
coroutineContext[Job]
key!
Thank you so much for your help ❤️
p
🤗 welcome
l
You can even do
Copy code
coroutineContext[Job]?.cancelChildren()