Home > Back-end >  Dispatchers.IO running on main thread?
Dispatchers.IO running on main thread?

Time:01-18

Consider the following code:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        lifecycleScope.launchWhenCreated {
            with(Dispatchers.IO) {
                if (Looper.myLooper() == Looper.getMainLooper()) {
                    throw Exception("we are on the main thread, though Dispatchers.IO is used")
                }
            }
        }
    }
}

Actually that does throw the exception

java.lang.Exception: we are on the main thread, though Dispatchers.IO is used

but why? Shouldn't Dispatchers.IO use a background thread?

(Hint: I am aware that in most cases I better use the ViewModel scope for coroutines, but that's not the question here - I want to understand why the current code throws the exception)

CodePudding user response:

You've mistaken scope function with coroutine one:

with(Dispatchers.IO){ } - a blocking call where lambdas body is scoped (this === Dispatchers.IO)

withContext(Dispatchers.IO){ } - suspending call executed in provided context (in this case it switches dispatcher) that returns a result to original context

  • Related