Manually clearing an Android ViewModel?

后端 未结 12 1056
独厮守ぢ
独厮守ぢ 2020-12-04 18:50

Edit: This question is a bit out of date now that Google has given us the ability to scope ViewModel to navigation graphs. The better approach (rather

12条回答
  •  星月不相逢
    2020-12-04 19:33

    If you check the code here you'll find out, that you can get the ViewModelStore from a ViewModelStoreOwner and Fragment, FragmentActivity for example implements, that interface.

    Soo from there you could just call viewModelStore.clear(), which as the documentation says:

     /**
     *  Clears internal storage and notifies ViewModels that they are no longer used.
     */
    public final void clear() {
        for (ViewModel vm : mMap.values()) {
            vm.clear();
        }
        mMap.clear();
    }
    

    N.B.: This will clear all the available ViewModels for the specific LifeCycleOwner, this does not allow you to clear one specific ViewModel.

提交回复
热议问题