12

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 Fragments 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.

nebulasmoothie
  • 371
  • 3
  • 7

2 Answers2

6
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    searchViewModel = ViewModelProvider().get(this, viewModelFactory)

This is correct, the common mistake tends to be the lifecycle owner used to observe the LiveData.

    // also in onViewCreated
    searchViewModel.observe(viewLifecycleOwner) { items ->
        ....
    }
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
4

There is no direct advantage of one to another as far as I know, since #onViewCreated is immediately being called after #onCreateView finishes. According to the docs:

void onViewCreated (View view, Bundle savedInstanceState)

Called immediately after onCreateView(LayoutInflater, ViewGroup, Bundle) has returned, but before any saved state has been restored in to the view. This gives subclasses a chance to initialize themselves once they know their view hierarchy has been completely created. The fragment's view hierarchy is not however attached to its parent at this point.

I normally prefer putting all initializations (if not related to my view-hierarchy) into #onViewCreated method. It has never been a problem in my case.

Onur D.
  • 515
  • 3
  • 11
  • awesome, thanks! yeah, it sounds like it's just about picking one of them and being consistent with it throughout one's codebase. – nebulasmoothie Feb 26 '19 at 19:59