ViewModelProviders is deprecated in 1.1.0
Looking at the Google docs for ViewModel
, they show the below sample code on how to get a ViewModel
:
val model = ViewModelProviders.of(this).get(MyViewModel::class.java)
When using the latest dependency android.arch.lifecycle:extensions:1.1.1
there is no such class ViewModelProviders
.
Going to the documentation for ViewModelProviders
, I saw a comment saying:
This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory
The problem is, when trying to use ViewModelProvider.AndroidViewModelFactory
, cannot find an equivalent of
method to get the instance of the ViewModel
.
What i tried doing:
ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(PlayerViewHolder::class.java)
Hence the name of the method create
, I get a new instance of the ViewModel every-time I call it, which is not what I am after.
Any ideas what is the replacement of deprecated code above?
Solution 1:
I use lifecycle-extensions 2.2.0
version:
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
It should 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 found another elegant way to achieve this, 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
Solution 2:
As @FantasyFang mentioned in his answer, use the lastest version for the lifecycle:lifecycle-extensions
which in this moment is 2.2.0-alpha03
. So you should add in your build.gradle file the following line:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha03'
For those who are using Java, to solve this, pass those arguments directly to ViewModelProvider's constructor:
MyViewModel viewModel = new ViewModelProvider(this, myViewModelFactory).get(MyViewModel.class);
Or if you don't use a factory, simply use:
MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);
Without passing your the factory object.
Solution 3:
Import
Deprecated From:
import androidx.lifecycle.ViewModelProviders;
To:
import androidx.lifecycle.ViewModelProvider;
Using
Deprecated From:
ViewModelProviders.of(this, provider).get(VM::class.java)
To:
ViewModelProvider(this, provider).get(VM::class.java)