Maybe this is a stupid question but I am somewhat puzzled by the following result of a test.
I am testing a suspend function with the following structure.
Copy code
val ioDispatcher: CoroutineDispatcher = <http://Dispatchers.IO|Dispatchers.IO>
suspend fun doSomething(ioDispatcher: CoroutineDispatcher) {
withContext(ioDispatcher) {
println("With context $ioDispatcher is running on ${getCurrentThreadName()}")
}
}
When I run the test and pass the defined
ioDispatcher
to the function
doSomething
the print statement results in the following output:
Copy code
With context <http://Dispatchers.IO|Dispatchers.IO> is running on DefaultDispatcher-worker-5 @coroutine#18
Why is this running on a DefaultDispatcher worker and not on an IODispatcher worker?
a
Alexandru Caraus
10/26/2024, 12:44 PM
On what dispatcher does it run before and after withContext?
๐ 1
m
Michael Paus
10/26/2024, 12:46 PM
I havenโt specified any. I run the test from IntelliJ via Gradle and the test function just calls runBlocking().
j
Joffrey
10/26/2024, 12:47 PM
These dispatchers share threads, for optimisation purposes. When switching from default to IO, it might not actually change threads