Shared ViewModel lifecycle for Android JetPack

2019-03-30 03:51发布

问题:

The documentation https://developer.android.com/topic/libraries/architecture/viewmodel#sharing describes how we can share the same ViewModel across the different Fragments.

I have some complicated pages in my single Activity app with a container and tabs fragments. Each such page has own ViewModel which should be shared with all contained fragments.

The key trick here is to use Activity instead of Fragment to hold my ViewModel.

The problem is that my Activity can have multiple pages with own models and holding the view model for particular page all the time is waste of device resources.

Is there any way to control the life-cycle of ViewModel to destroy it when user leaves the page?

I thought to use the container fragment instead of Activity:

model = ViewModelProviders.of(getPageContainerFragment()).get(SharedViewModel.class);

But found this idea not so good because all children fragments should know about the parent which could be not so good.

Is there any alternatives to tackle properly such case?