Shared ViewModel lifecycle for Android JetPack

﹥>﹥吖頭↗ 提交于 2019-12-03 06:51:36

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.

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