Looking at the Google docs for ViewModel
, they show the below sample code on how to get a ViewModel
:
val model = ViewModelProviders
Early in 2020, Google have deprecated the ViewModelProviders class, in version 2.2.0 of the androidx lifecycle library.
It's no longer necessary to use ViewModelProviders to create an instance of a ViewModel, you can pass your Fragment or Activity instance to the ViewModelProvider constructor instead.
If you use the code like:
val viewModel = ViewModelProviders.of(this).get(CalculatorViewModel::class.java)
you'll get a warning that ViewModelProviders has been deprecated.
To avoid using deprecated libraries, make the following changes:
In the build.gradle (Module: app) file, use version 2.2.0 of the lifecycle components:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.activity:activity-ktx:1.1.0"
If you want to use the ViewModel from a Fragment instead, use
implementation "androidx.fragment:fragment-ktx:1.2.2"
fragment-ktx automatically includes activity-ktx, so you don't need to specify both in the dependencies.
You need to specify Java 8 in the android section :
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.kgandroid.calculator"
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner
"androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
kotlinOptions { jvmTarget = "1.8" }
}
In your Fragment or Activity, change the import to:
import androidx.activity.viewModels
The code to create a ViewModel then becomes:
val viewModel: CalculatorViewModel by viewModels()
instead of
val viewModel = ViewModelProviders.of(this).get(CalculatorViewModel::class.java)
Use the viewModel object as :
val viewModel: CalculatorViewModel by viewModels()
viewModel.newNumber.observe(this, Observer {
stringResult -> newNumber.setText(stringResult)
})
where newNumer is a LiveData object
In a Fragment that you want to share the Activity's ViewModel, you'd use
val viewModel: CalculatorViewModel by activityViewModels()
That's the equivalent of passing the Activity instance in the (deprecated) ViewModelProviders.of()
function.