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 boing to affect something if in future I will add support of kotlin multiplatform?
On Android, we typically use the Main dispatcher as the default one. If you use libraries that are suspending instead of blocking, and you don't do any complex calculations, in practice you can often use only Dispatchers. Main . If you do some CPU-intensive operations, you should run them on Dispatchers.
Dispatchers. Main - Use this dispatcher to run a coroutine on the main Android thread. This should be used only for interacting with the UI and performing quick work. Examples include calling suspend functions, running Android UI framework operations, and updating LiveData objects.
Kotlin launch vs async coroutines The launch launches a new coroutine concurrently with the rest of the code, which continues to work independently. The async creates a coroutine and can return the result of the asynchronous task. Start a coroutine that returns some result.
We can for example schedule coroutines on a Java Executor or on Android main looper. However, we can't schedule coroutines on just any thread, it has to cooperate.
Then I discovered that it defaults to viewModelScope.launch(Dispatchers.Default) {}.
No, viewModelScope.launch()
defaults to Dispatchers.Main
. 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.
Is that right?
No, sorry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With