Launching a coroutine in ViewModel vs LifeCycleOwner (Activities/fragments)

Viewed 912

Is it better to launch a coroutine in the ViewModel or to mark the ViewModel function with suspend modifier and launch the coroutine in the activity/fragment itself?

Launching in the ViewModel:

class MainViewModel: ViewModel() {
  fun addNewItem(item: Item) {
    viewModelScope.launch {
      // Add the item to database
    }
  }
}
class ItemsFragment: Fragment() {
  fun onButtonClick() {
    viewModel.addNewItem(Item())
  }
}

Launching in the LifeCycleOwner:

class MainViewModel: ViewModel() {
  suspend fun addNewItem(item: Item) {
    // Add the item to database
  }
}
class ItemsFragment: Fragment() {
  fun onButtonClick() {
    lifecycleScope.launchWhenStarted {
      viewModel.addNewItem(Item())
    }
  }
}
1 Answers

It really depends on your use-case and if you'd like to tie the task to the viewModelScope or the view's lifecycleScope.

For better understanding consider the following two examples:

  1. The user triggers a refresh - probably you don't want to tie this to the view's lifecycleScope, since in case of an orientation-change your task will be killed and you'll have to restart the fetching of data again.
  2. Animation or other View related task - suppose you have to do some calculations for an animation that's related to how the view is laid out. In this case after an orientation-change you might have to recalculate things, since the view changed.

Generally speaking you're more likely to bump into the first scenario I believe.

In your case adding an item goes into the 1st use-case, since suppose you're launching from the view directly and using lifecycleScope from Fragment/Actvity, in that case if the suspend saving is still running and an orientation-change happens, the task will get killed and your user will wonder why the item wasn't added.

With that said, db operations generally run so fast that the above scenario will be hard to reproduce, but throw in an api request or delay for testing purposes and you can check out the theory.

Related