This is my note for Udemy lesson: Advanced Android Bootcamp 2024.
1. Add Dependencies
In app/build.gradle
, add the following dependencies:
dependencies { def lifecycle_version = "2.7.0" implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" }
You can check the latest version through this website
2. Create a ViewModel
import androidx.lifecycle.ViewModel class MainActivityViewModel: ViewModel() { ... }
3. Use the ViewModel in Activity
class MainActivity: AppCompatActivity() { private lateinit var viewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProvider(this)[MainActivityViewModel::class.java] } }