private val viewModel: GameViewModel by viewModels()
Imports:
dependencies {
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
// LiveData
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.5.1'
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
implementation 'androidx.fragment:fragment-ktx:1.5.5'
}
I want to implement ViewModel into my app, but I cant import viewModels()
CodePudding user response:
To use ViewModel in your app, you will need to add the following dependency in your build.gradle file:
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
Then, declare a ViewModel in your activity, fragment, or other class. For example:
private val viewModel: GameViewModel by viewModels()
Finally, use the ViewModel within your activity by calling its methods and properties.