Looking at the Google docs for ViewModel
, they show the below sample code on how to get a ViewModel
:
val model = ViewModelProviders
ViewModelProviders.of() has been deprecated.
Use ViewModelProvider constructors directly as they now handle the default ViewModelProvider.Factory role.
mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
In case you watch a video from Udacity
where you create a GameViewModel
and you do not want to write deprecated code just replace:
viewModel = ViewModelProviders.of(this).get(GameViewModel::class.java)
with the following code:
viewModel = ViewModelProvider(this).get(GameViewModel::class.java)
and return back to reading ASAP!!
I use lifecycle-extensions 2.2.0
version:
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
It should be work, using ViewModelProvider
constructor.
// With ViewModelFactory
val viewModel = ViewModelProvider(this, YourViewModelFactory).get(YourViewModel::class.java)
//Without ViewModelFactory
val viewModel = ViewModelProvider(this).get(YourViewModel::class.java)
2020/5/15 Update
I find another elegant way to achieve, Android KTX can help
implementation "androidx.fragment:fragment-ktx:1.2.4"
val viewmodel: MYViewModel by viewModels()
val viewmodel: MYViewModel by viewModels { myFactory } //With factory
Ref: https://developer.android.com/reference/kotlin/androidx/fragment/app/package-summary#viewmodels
2020/06/25: corrected the case of the delegate
it should work this way
viewModel = ViewModelProviders.of(this@MainActivity).get(MainActivityViewModel::class.java)
If you use Kotlin, you can use the property delegate viewModels()
like this:
val viewModel: YourViewModel by viewModels()
Source: https://forums.bignerdranch.com/t/solution-to-deprecated-method-viewmodelproviders-of/16833
Use this:
YourViewModel yourViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(YourViewModel.class);