In the android-architecture-components/GithubBrowserSample repo, the Fragment#onViewCreated
lifecycle method is being used for ViewModel
instantiation (with the Fragment
's scope) for the Fragment
s that use the combination of databinding + LiveData
+ ViewModel
:
From SearchFragment.kt
of that repo ^:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
searchViewModel = ViewModelProviders.of(this, viewModelFactory)
...
}
Is there any official guideline or consensus as to which of these Fragment
lifecycle methods such as onAttach
, onCreate
, onViewCreated
, or onActivityCreated
is the best/safest place to instantiate the Fragment
's ViewModel
using the ViewModelProviders.of(fragment, viewModelFactory)
method? (given the databinding + LiveData
combo, if that makes a difference)
Trying to make sense of the general advantages/disadvantages of putting ViewModel
instantiation into any of the early lifecycle methods such as onAttach
/onCreate
, for example (after calling super
, of course).
Thanks in advance.