how to use viewmodel in compose

View Model in Jetpack Compose

Introduction

In this post, we will learn about how to use ViewModel in Jetpack Compose. ViewModel is an essential part of the Jetpack library. It helps us manage the UI-related data in a lifecycle-aware way, allowing us to handle configuration changes and prevent data loss during screen rotations.

Prerequisites

Before we start, make sure you have the following dependencies added to your app-level build.gradle file:
groovy
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha04"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.0"

Creating a ViewModel

To create a ViewModel, we need to extend the ViewModel class provided by the Jetpack libraries.

kotlin
class MyViewModel : ViewModel() {
// Add your LiveData properties and methods here
}

Accessing the ViewModel in Composable

To access the ViewModel in a Composable function, we can use the androidx.lifecycle.viewmodel Kotlin extension property called viewModel.

kotlin
@Composable
fun MyScreen() {
val viewModel: MyViewModel = viewModel()
// Use the viewModel instance here
}

Observing LiveData in Composable

To observe a LiveData object from the ViewModel in Jetpack Compose, we can use the collectAsState extension function provided by the State class.

“`kotlin
@Composable
fun MyScreen() {
val viewModel: MyViewModel = viewModel()
val myData: State = viewModel.myLiveData.collectAsState()

// Render the UI using myData

}
“`

Modifying LiveData in ViewModel

To modify the LiveData from the ViewModel, we can use the viewModelScope provided by the viewModel property.

“`kotlin
class MyViewModel : ViewModel() {
private val _myLiveData = MutableLiveData()
val myLiveData: LiveData get() = _myLiveData

fun updateData(newValue: MyDataType) {
    viewModelScope.launch {
        _myLiveData.value = newValue
    }
}

}
“`

Conclusion

In this post, we have learned how to use ViewModel in Jetpack Compose. ViewModel helps us manage UI-related data in a lifecycle-aware way, reducing the risk of data loss during configuration changes. We can observe LiveData objects and modify them within the ViewModel using the lifecycle scope provided by the viewModelScope property.