architecture-components-samples: ViewModel's onCleared is not be call after fragment is destroyed.

I have a very simple ViewModel.

class TestViewModel: ViewModel() {
    override fun onCleared() {
        super.onCleared()
        Log.d("TEST", "clear")
    }
}

and I use it in a fragment

class TestFragment() {
    //....
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        vm = ViewModelProviders.of(this).get(TestViewModel::class.java)
    }
}

and the onCleared method is not be called after activity finished.

If I want the method to be called, I have to remove fragment manually before finish activity.

I am not sure it is feature or bug.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 2
  • Comments: 17 (1 by maintainers)

Most upvoted comments

Issue still exists in 2.4.1

viewmodel is not being cleared still for version 2.3.1

After wasting ANOTHER day troubleshooting why my ViewModel wasn’t being cleared when my DialogFragment’s onDestroy method was called, I think I’ve isolated the culprit. In my DialogFragment, I was instantiating the VM this (wrong) way;

private val vm: MyViewModel by activityViewModels()

Changing it to this (right) way solved it:

private val vm: MyViewModel by viewModels()

Apparently, the by activityViewModels delegate automatically scopes the VM lifetime to the lifetime of DialogFragment’s host Activity instead of the DialogFragment itself. I think this explains why the VM wasn’t clearing. I’ll save ranting about the absurd complexity of Android for another post.

What’s about same bug in androidX? androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha05

Update: seems like my case slightly different, i will open issue in issuetracker.

Same bug in androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0-alpha05

For users who have this issue with fragments linked to BottomNavigationView, the viewModel might not be getting cleared due to the support added for multiple back stacks. You can refer to this article by Ian Lake where he talks about when exactly a fragment is removed from such back stacks and consequently the view model scoped to them is cleared.

Credits to this reddit thread by u/psteiger.