I have an app with a RootFragment containing a ViewPager2, presenting multiple ChildFragment.
The RootFragment has a RootViewModel, and each ChildFragment also has a ChildViewModel.
Running the app, I can see that the root fragment's view model is being created once and preserved through rotations etc - this is exactly what I expected to happen.
However, when I scroll through the child fragments and back again it looks like the ChildVieWModels are being recreated each time the ViewPager2 destroys/recreates the fragments to display. This isn't what I need at all!
How can I get the view models of the child fragment to remain even though the child fragments themselves are being destroyed and recreated by the ViewPager2?
My child fragment is requesting a view model like this:
private val viewModel: ChildViewModel by viewModels()
I have also tried scoping the child view model to the parent fragment but that just means each child fragment gets the same instance of ChildViewModel, which isn't quite right either:
private val viewModel: ChildViewModel by viewModels({ requireParentFragment() })
I've looked at the samples for ViewPager2 but none of them seem to have a view model in their child fragments.
What have I misunderstood here?