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 that Tim types in the videos, along the lines of:
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.
1. In the build.gradle (Module: app) file, use version 2.2.0 of the lifecycle components:
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
Also add
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.
2. You need to specify Java 8 in the android section (line 18 below):
android { compileSdkVersion 28 defaultConfig { applicationId "academy.learnprogramming.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" } }
3. In your Fragment or Activity, change the import to:
import androidx.activity.viewModels
3. The code to create a ViewModel then becomes:
val viewModel: CalculatorViewModel by viewModels()
instead of val viewModel = ViewModelProviders.of(this).get(CalculatorViewModel::class.java)
In a Fragment that you want to share the Activity's ViewModel, you'd use
val viewModel: TaskTimerViewModel by activityViewModels()
That's the equivalent of passing the Activity instance in the (deprecated) ViewModelProviders.of()
function.
After those changes, you're no longer using the deprecated ViewModelProviders class, and are creating the ViewModel in a more Kotlin-like manner.
The androidx.activity:activity-ktx
and androidx.fragment:fragment-ktx
libraries require Java 8 bytecode. If you need to stick with Java 1.7 bytecode for some reason, you can avoid adding a dependency on those libraries and create your ViewModel instances using code like:
val viewModel = ViewModelProvider(this).get(CalculatorViewModel::class.java)