Search code examples
androidkotlinkotlin-coroutineskotlin-android-extensions

What is the difference between Dispatchers.Main and Dispatchers.Default in Kotlin coroutines?


What is the difference between Dispatchers.Main and Dispatchers.Default in Kotlin coroutines?

I used viewModelScope.launch {} and launch block as expected is executed on UI thread. Then I discovered that it defaults to viewModelScope.launch(Dispatchers.Default) {}.

This was a bit confusing to me as I thought that I should use Dispatchers.Main to perform operations on the UI thread.

So far it looks like that on Android Dispatchers.Default is defaulting to Dispatchers.Main. Is that right?

Is there any drawbacks if I use one or another or they are interchangeable? If they are interchangeable on Android, is it going to affect something if in future I will add support of kotlin multiplatform?


Solution

  • Then I discovered that it defaults to viewModelScope.launch(Dispatchers.Default) {}.

    No, viewModelScope.launch() defaults to Dispatchers.Main.immediate. Google overrides the ordinary default launch() dispatcher, which is Dispatchers.Default. I recommend always specifying the dispatcher, rather than having to make people guess which one gets used in which circumstances.