Search code examples
androidandroid-fragmentsmvvmviewmodelandroid-viewmodel

When getting the ViewModel in a fragment, should I provide "viewModelStore" or "this" as the ViewModelStore to the ViewModelProvider() method


Inside my fragment class, when I am getting my viewModel, I can write my code in two different ways.

  • Using "viewModelStore"
ViewModelProvider(viewModelStore, viewModelFactory).get(FragmentViewModel::class.java)
  • Using "this"
ViewModelProvider(this, viewModelFactory).get(FragmentViewModel::class.java)

My question is, does any difference exist between the two alternatives, and if yes which one is the preferable approach?


Solution

  • If you're providing your own ViewModelProvider.Factory, then there's no difference, so just use what is easier, this.

    Of course, if you're in Kotlin, you don't need to use ViewModelProvider directly at all, you'd instead want to use Fragment KTX and use

    val viewModel: FragmentViewModel by viewModels { viewModelFactory }
    

    Note that if you were not using your own factory, you should always pass in a ViewModelStoreOwner (i.e., this) instead of just passing in the ViewModelStore since the Javadoc explicitly mentions:

    This method will use the default factory if the owner implements HasDefaultViewModelProviderFactory. Otherwise, a ViewModelProvider.NewInstanceFactory will be used.

    The ViewModelStore constructor is not able to get the correct default factory.