Reputation: 2668
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?
Upvotes: 21
Views: 10094
Reputation: 1006819
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.
Upvotes: 22