I have tried to read this, but I think I cant find the solution.
say I have FragmentA and Fragment B. I move to fragment B using this code
val nextDestination = AFragmentDirections.actionToB()
findNavController().navigate(nextDestination)
when I back from fragment B to fragment A, onDestroy
in my fragment is called and then onCleared
on my ViewModel is also get called.
but when I rotate the phone (configuration changes), when onDestroy
is called, then onCleared
is NOT called.
so I previously assume, when onDestroy
called, then onCleared
is also called. but it is not. why there is different behaviour like this ? when configuration changes is different from fragment navigation ?
I am confused when exactly the onCleared
is called
The whole point of a ViewModel is to survive configuration changes as per the ViewModel documentation, so it is expected that ViewModels are not cleared over a configuration change.
However, each ViewModel is associated with a ViewModelStoreOwner
. This could be your activity or it could be a Fragment. It is up to that ViewModelStoreOwner
to understand when it is being destroyed due to a temporary change (such as a configuration change) or a permanent destruction. It is only in that permanent destruction that onCleared()
for each ViewModel is called.
For an activity, that permanent destruction happens when the activity is finished (i.e., finish()
is called or the behavior of onBackPressed()
leads to finish()
being called).
For a Fragment, that permanent destruction happens when the Fragment is popped off the back stack. This is what happens when you pop fragment B off the back stack and return to Fragment A - Fragment B is removed from the FragmentManager, it goes through onDestroy()
, and its ViewModels are cleared.
Fragment A will have the same thing happen to it once it is popped off the back stack or, if it is the only thing on the back stack, when the activity is finished when you hit the system back button.