Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ViewModel correctly to share, mutate or observe data between different layers in an android app using Jetpack Compose?

I am new to Jetpack compose, when following the example video from https://developer.android.com/develop/ui/compose/state at 4:00

I found that the viewModel() is missing in my project.

class HelloViewModel : ViewModel() {

    private var _name = MutableLiveData("View Model")
    val name: LiveData<String> = _name

    fun setName(newName: String) {
        _name.value = newName
    }

}

// In the latest version of Jetpack compose
// viewModel() is missing here as a default value for helloViewModel variable
// And I don't know what dependencies should be implemented for my project
@Composable
fun ViewModelTest(helloViewModel: HelloViewModel = viewModel()) {

    // This line errors, since helloModel.name doesn't have a method called `observeAsState()`
    val name by helloViewModel.name.observeAsState()

    // A text composable
    Text(name.value)

    // A Button, once clicked, replace the text of Text composable to "ViewModel changed"
    Button(onClick = { helloViewModel.setName("ViewModel changed") }) {
        Text(text = "Text")
    }
}

Any suggestions?

// default value for helloViewModel should be viewModel()
fun ViewModelTest(helloViewModel: HelloViewModel = viewModel())

// observe the name as a state
val name by helloViewModel.name.observeAsState()
like image 734
Loskau Avatar asked Nov 17 '25 17:11

Loskau


1 Answers

To be able to use the viewModel() function, you need to add the following dependency to your module's build.gradle file:

for build.gradle (Groovy):

implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.8.5'

for build.gradle.kts (Kotlin):

implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.8.5")
like image 144
BenjyTec Avatar answered Nov 20 '25 07:11

BenjyTec