Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if coroutines are using the same context?

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.

like image 245
J_Strauton Avatar asked Sep 21 '25 00:09

J_Strauton


1 Answers

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)
like image 176
Tenfour04 Avatar answered Sep 22 '25 14:09

Tenfour04