I have two Coroutines and I want to check if they are running in the same context/Dispatcher. This is a simplified version of my problem, but the answer will apply to the thing I am doing:
@Test
fun test() {
val io = runBlocking(Dispatcher.IO) {
coroutineContext
}
val nonIo = runBlocking() {
coroutineContext
}
assertNotEquals(io, nonIo)
}
However, this is a bad test because I am simply comparing two distinct objects. I want to compare if they use Dispatcher.IO
or not.
I think you mean to ask if the the coroutines use the same Dispatcher, right? A dispatcher is just one piece of a CoroutineContext. You can use the get
function of a CoroutineContext with the key ContinuationInterceptor
to retrieve the Dispatcher.
val io = withContext(Dispatchers.IO) {
coroutineContext[ContinuationInterceptor]
}
val nonIo = withContext(Dispatchers.Default) {
coroutineContext[ContinuationInterceptor]
}
assertNotEquals(io, nonIo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With