Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 boing to affect something if in future I will add support of kotlin multiplatform?

like image 458
Vadims Savjolovs Avatar asked Jan 08 '20 13:01

Vadims Savjolovs


People also ask

What is the default dispatcher in coroutines?

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.

What is dispatcher Main?

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.

What is the difference between launch and async in Kotlin coroutines?

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.

Can coroutines run on main thread?

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.


1 Answers

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.

like image 71
CommonsWare Avatar answered Oct 21 '22 08:10

CommonsWare