Warm tip: This article is reproduced from stackoverflow.com, please click
android android-architecture-components viewmodel

Shared viewModel achived fragment lifecycle

发布于 2020-03-27 10:15:16

How I can use shared viewModel with fragments without activity? Like in code but in place of requireActivity() use ParentFragment. In this case when ParentFragment will destroyed, SharedViewModel is cleared, but when I provide SharedViewModel from activity, it not cleared when ParentFragment destroyed.

And I use Navigation Components, which mean that I can`t set tag for fragment and then use findFragmentByTag()


class ParentFragment:Fragment{

    override fun onCreate(savedInstanceState: Bundle?) {
      var viewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class)
    }
}

class ChildFragment:Fragmnet{
   override fun onCreate(savedInstanceState: Bundle?) {
      var viewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class)
    }

}


Questioner
Alexander Kazantsev
Viewed
155
dhabensky 2019-07-09 14:27

You can try scoped-vm - it allows you to request ViewModel for scope identified by a String key. Scope lives till the last fragment that requested ViewModel gets destroyed, then ViewModel gets cleared.

You can use this code to obtain SharedViewModel both in ParentFragment and ChildFragment.

ScopedViewModelProviders
     .forScope(this, "scope")
     .of(requireActivity())
     .get(SharedViewModel::class.java)