Shared ViewModel lifecycle for Android JetPack

后端 未结 2 1188
攒了一身酷
攒了一身酷 2021-02-08 15:53

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

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-08 16:37

    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.

提交回复
热议问题