Sobes.tech
Junior — Middle

Milliseid lähenemisviise ja rakendusi tead ViewModel mustrile?

sobes.tech AI

Vastus AI-lt

The ViewModel pattern in Android is used to store and manage UI data, taking into account 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 the recreation of Activity/Fragment (e.g., during screen rotation). The ViewModel lives as long as the UI component is alive.

  • ViewModel with LiveData — often, the 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 the UI, but without using AndroidX, for example, in pure MVVM.

Example of using the standard ViewModel with LiveData:

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

    fun loadData() {
        // load data, e.g., 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()