Sobes.tech
Junior — Middle

Can you explain how to implement the Model-View-ViewModel architectural pattern and what its main components are?

sobes.tech AI

Answer from AI

The architectural pattern Model-View-ViewModel (MVVM) divides application logic into three main components:

  • Model — responsible for data handling and business logic. This can include databases, network requests, repositories.
  • View — UI components (activities, fragments) that display data and respond to user actions.
  • ViewModel — an intermediary between Model and View. It contains presentation logic, prepares data for display, and handles user events.

ViewModel typically uses Observable objects (e.g., LiveData in Android) so that the View can subscribe to data changes and update automatically.

Example in Kotlin using LiveData:

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

    fun loadData() {
        // Get data from Model (e.g., repository)
        _data.value = "Hello, MVVM!"
    }
}

// In Activity or Fragment
viewModel.data.observe(this) { value ->
    textView.text = value
}