0
0
Android Kotlinmobile~5 mins

State in ViewModel in Android Kotlin

Choose your learning style9 modes available
Introduction

We use state in ViewModel to keep data safe when the screen changes or the app rotates. It helps the app remember what the user was doing.

When you want to keep user input safe during screen rotation.
When you need to share data between different parts of the app without losing it.
When you want to separate UI code from data handling for cleaner code.
When you want to update the screen automatically when data changes.
Syntax
Android Kotlin
class MyViewModel : ViewModel() {
    private val _state = MutableLiveData<String>()
    val state: LiveData<String> get() = _state

    fun updateState(newValue: String) {
        _state.value = newValue
    }
}

Use MutableLiveData inside ViewModel to hold data that can change.

Expose LiveData to the UI to observe changes without allowing direct modification.

Examples
This example shows a counter that increases by one when increment() is called.
Android Kotlin
private val _count = MutableLiveData<Int>(0)
val count: LiveData<Int> get() = _count

fun increment() {
    _count.value = (_count.value ?: 0) + 1
}
This example updates a text value that the UI can observe and display.
Android Kotlin
private val _text = MutableLiveData<String>()
val text: LiveData<String> get() = _text

fun setText(newText: String) {
    _text.value = newText
}
Sample App

This ViewModel holds a count number. When you press a button, it increases the count. The UI listens to changes and updates the displayed number automatically.

Android Kotlin
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class CounterViewModel : ViewModel() {
    private val _count = MutableLiveData(0)
    val count: LiveData<Int> get() = _count

    fun increment() {
        _count.value = (_count.value ?: 0) + 1
    }
}

// In your Activity or Fragment:
// val viewModel = ViewModelProvider(this).get(CounterViewModel::class.java)
// viewModel.count.observe(this) { value ->
//     textView.text = "Count: $value"
// }
// button.setOnClickListener { viewModel.increment() }
OutputSuccess
Important Notes

Always keep your UI code separate from data logic by using ViewModel.

LiveData automatically updates the UI when data changes, so you don't have to refresh manually.

Remember to observe LiveData with lifecycle awareness to avoid memory leaks.

Summary

State in ViewModel keeps data safe during screen changes.

Use MutableLiveData inside ViewModel and expose LiveData to UI.

UI observes LiveData to update automatically when data changes.