Inside my fragment class, when I am getting my viewModel, I can write my code in two different ways.
ViewModelProvider(viewModelStore, viewModelFactory).get(FragmentViewModel::class.java)
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?
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, aViewModelProvider.NewInstanceFactory
will be used.
The ViewModelStore
constructor is not able to get the correct default factory.