How does fragment restores its state

48 Views Asked by At

I have an activity and fragments. The activity is controlling navigation via observing navigation LiveData state.

sealed class Navigation {
   object Destination1: Navigation()
   object Destination2: Navigation()
}

On each change it replaces a fragment in a container (each time a new instance of fragment is created for each destination).

This however does not work when I try to save the state of the fragment. In activity:

viewModel.navigation.observe(viewLifecycleOwner) {
    supportFragmentManager.commit {
        replace(R.id.container, fragmentInstance)
        addToBackStack(null)
    }
}

I tried to implement the ViewModel SavedStateHandle but the state is not saved. The Handle is empty when I have "don't keep activities" setting ON and I minimize and then maximize the app.

What am I doing wrong? Is it possible to save state of the Fragment?

How to plug the activity's savedInstanceState into the fragments if I create them by observing LiveData? Is the LiveData approach a problem?

0

There are 0 best solutions below