Sobes.tech
Junior — Middle

What approaches and implementations of the ViewModel pattern are you familiar with?

sobes.tech AI

Answer from AI

The ViewModel pattern in Android is used for storing and managing UI data considering the lifecycle of components such as Activity or Fragment. Main approaches and implementations:

  • Android Architecture Components ViewModel — a class from the androidx.lifecycle library that allows data to be preserved during Activity/Fragment recreation (for example, during screen rotation). ViewModel lives as long as the UI component lives.

  • ViewModel with LiveData — often, ViewModel contains LiveData to automatically update the UI when data changes.

  • Custom ViewModel — you can implement your own ViewModel pattern, separating logic and data from UI, but without using AndroidX, for example, in pure MVVM.

Example of using a standard ViewModel with LiveData:

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

    fun loadData() {
        // load data, for example from a repository
        _data.value = "Sample data"
    }
}

// In Activity or Fragment
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
viewModel.data.observe(this) { value ->
    textView.text = value
}
viewModel.loadData()
What approaches and implementations of the ViewModel… - sobes.tech