Sobes.tech
Junior — Middle

How to implement data storage and management within a ViewModel?

sobes.tech AI

Answer from AI

To store and manage data state within ViewModel in Android, MutableLiveData or StateFlow are commonly used.

  • MutableLiveData is a class that allows storing data and notifying observers (usually UI) about changes. In ViewModel, a private MutableLiveData is created, and only LiveData is exposed externally for reading, to prevent state modification from the UI.

  • StateFlow is part of Kotlin Coroutines, representing a stateful flow. It is more modern and convenient for reactive programming.

Example with LiveData:

class MyViewModel : ViewModel() {
    private val _data = MutableLiveData<String>()
    val data: LiveData<String> = _data

    fun updateData(newValue: String) {
        _data.value = newValue
    }
}

Example with StateFlow:

class MyViewModel : ViewModel() {
    private val _state = MutableStateFlow("initial")
    val state: StateFlow<String> = _state

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

Thus, ViewModel stores the state, and the UI subscribes to changes and updates automatically, ensuring separation of responsibilities and resilience to configuration changes.