SharedViewModel not clearing when poping fragment

Viewed 1664

I'm using a shared view model like here

But the problem is that when I clear my last fragment, I want to clear the viewmodel, or kill its instance, but somehow it survives when I leave the last fragment that uses it

How can I programatically clear this viewmodel ?

I use it like this

Fragment A

private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated() {

     model.getTotal().observe(viewLifecycleOwner, Observer { cartTotal ->
                total = cartTotal
            })

    }

From fragment B I sent the total

Fragment B

private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated() {

     model.setTotal = 10
}

But when leaving Fragment A with that data (doing popBackStack since I'm using navigation components) it does not clear the viewmodel, instead when I open again my fragment , the data stills there

I suspect that the viewmodel is tied with my Container Activity and not the lifecycle of the fragments itself, so

How can I remove the instance or clear my viewmdel when I hit my last fragment ?

Thanks

2 Answers

If you want to get a ViewModel associated with a parent fragment, your inner fragment should follow the by viewModels JavaDoc and use:

val viewmodel: MYViewModel by viewmodels ({requireParentFragment()})

This says to use the parent Fragment as the owner of your ViewModel.

(The parent fragment would use by viewModels() as it is accessing its own ViewModels)

you can also clear viewModelStore manually after Fragment A destroyed. something like this :

override fun onDetach() {
    super.onDetach()
    requireActivity().viewModelStore.clear()
}

then your viewModel instance will be cleared. for checking this work you can debug onCleared method of your viewModel.

Related