Ad

Shared ViewModel Achived Fragment Lifecycle

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)
    }

}


Ad

Answer

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)
Ad
source: stackoverflow.com
Ad