Using ViewModel in Jetpack Compose
This is a short memo about using ViewModel in Jetpack Compose.
Add Dependencies
- You should use the latest version of the dependencies written in the document below.
- lifecycle-viewmodel-compose
- runtime-livedata
// To use 'viewModel()` in composable implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07" // To use `observeAsState' in composable implementation("androidx.compose.runtime:runtime-livedata:1.0.0-rc02")
create ViewModel
- I think ViewModel is the same to what it used to be in not Composable.
class MyViewModel(): VIewModel() { private val _name = MutableLiveData("") val name: LiveData<String> = _name }
Observe LiveData in Compose
@Composable fun NameComposable(viewModel: MyViewModel = viewModel()) { val name: String by viewModel.name // use name or change name }
It works!