Home > Software design >  viewModelScope.launch with the viewModel variable onDestory() not working
viewModelScope.launch with the viewModel variable onDestory() not working

Time:01-03

The following coe prints only "onDestory", not "launch". But if I modify the code like the second block, then "launch" is printed. Why is that? Is class member variable destroyed before onDestroy()?

  lateinit var viewModel: ArticleViewModel;

  override fun onCreate(savedInstanceState: Bundle?)
  {
    super.onCreate(savedInstanceState)
    viewModel = ViewModelProvider(this)[ArticleViewModel::class.java];
  ....

  override fun onDestroy()
  {
    super.onDestroy()
    Log.d("stack", "onDestroy");

    viewModel.viewModelScope.launch(Dispatchers.IO)
    {
      Log.d("stack", "launch");
    }
  }

Modification

  override fun onDestroy()
  {
    super.onDestroy()
    Log.d("stack", "onDestroy");
    val vm = ViewModelProvider(this)[ArticleViewModel::class.java];
    vm.viewModelScope.launch(Dispatchers.IO)
    {
      Log.d("stack", "launch");
    }
  }

CodePudding user response:

my answer below is based on the assumption that your Activity is finishing and not being recreated (which is what would happen in a configuration change for example)

The viewModelScope is a special scope that follows the lifecycle of the ViewModel. Which means that if the viewModel.onCleared() is called then the viewModelScope is being canceled. Side note: if you try to launch a coroutine in a canceled scope, nothing will happen.

Now take a look at the ViewModel Lifecycle If your activity is finishing, then the onCleared() will get called soon after the onDestroy of your Activity.

Coming to your code, I think that the job you are trying to start, is never getting started because your onCleared is called before the Dispatchers.IO manages to start the job

The second block of code (and I am making a guess here) is probably creating another instance of the ViewModel that somehow manages to outlive the destruction of the activity, since it receives no activity lifecycle calls (nothing else is happening after onDestroy). This is probably a bug. In my opinion you shouldn't be allowed to request a viewmodel from the provider while inside onDestroy

  • Related