What is the reason behind viewModelScope defaulting to MainThread?

Viewed 457

What is the reason behind viewModelScope defaulting to MainThread when most of the use cases are using as a background thread?

I still can't think of one example in my project that require using the main thread in ViewModel.

Also, is there a better/shorter way than writing as below?

viewModelScope.launch(Dispatchers.Default) {
   // codes here
}
1 Answers

Couple of reasons:

  1. ViewModel is probably the closest layer to the UI, which means a lot of logic here is involved in updating the UI => launching in any other thread will mean that you'll have to switch back to the Main for updating things
  2. Using any other dispatcher implies, that one knows what kind of operations will happen in the VM (like IO operations or some computing maybe?)

In general I think it's a good practice, to not handle thread switching in your VM and handle on the layer, which essentially knows what kind of operation will be run. For example if you have a VM -> Repository -> LocalSource (database operations) & RemoteSource (networking), then I'd do the switching to the IO thread in the Remote and Local sources.

Related