Shared ViewModel lifecycle for Android JetPack

淺唱寂寞╮ 提交于 2019-12-04 11:52:13

问题


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?


回答1:


If I get it right, your question is "how to free up resources" not "how to clear viewmodel".
So, you can make your viewmodels as light as possible, like this:

abstract class MyViewModel: ViewModel() {
    abstract fun freeResources()
}

and call vm.freeResources() in your OnPageChangeListener or OnTabSelectedListener or whichever listener you use, when page is changed.
In this case your should obtain viewModel using activity scope.

Alternatively, if you really want your viewmodel to be onCleared() and then the new one created, I can suggest using scoped-vm library. It allows your to request viewmodels for a scope identified by a string name.

ScopedViewModelProviders
     .forScope(fragment, "scope")
     .of(activity)
     .get(MyViewModel::class.java)

Scope gets cleared (so are viewmodels in it) as soon as last fragment that requested something from that scope gets destroyed. So use different scopes for your pages.
But, in this case you should double-check the lifecycle of your fragments: if your PagerAdapter holds them for re-use, the scope will never be cleared, and only manual approach will help you.



来源:https://stackoverflow.com/questions/53236574/shared-viewmodel-lifecycle-for-android-jetpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!