Manually clearing an Android ViewModel?

后端 未结 12 1044
独厮守ぢ
独厮守ぢ 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:16

    If you don't want the ViewModel to be scoped to the Activity lifecycle, you can scope it to the parent fragment's lifecycle. So if you want to share an instance of the ViewModel with multiple fragments in a screen, you can layout the fragments such that they all share a common parent fragment. That way when you instantiate the ViewModel you can just do this:

    CommonViewModel viewModel = ViewModelProviders.of(getParentFragment()).class(CommonViewModel.class);
    

    Hopefully this helps!

提交回复
热议问题