Sobes.tech
Junior — Middle

How is the interaction between View and ViewModel implemented in the MVVM pattern?

sobes.tech AI

Answer from AI

In the MVVM (Model-View-ViewModel) pattern, the interaction between View and ViewModel occurs through data binding and change notifications.

Main mechanisms:

  • Data Binding — The View binds to the public properties and commands of the ViewModel. When data in the ViewModel changes, the View automatically updates.
  • LiveData / Observable — In Android, LiveData or other observable objects are often used so that the ViewModel can notify the View about changes.
  • Commands — The ViewModel provides commands that the View invokes during user interactions (e.g., button clicks).

Example in Kotlin with LiveData:

class MyViewModel : ViewModel() {
    val text = MutableLiveData<String>()

    fun updateText(newText: String) {
        text.value = newText
    }
}

// In Activity or Fragment
viewModel.text.observe(viewLifecycleOwner) { updatedText ->
    textView.text = updatedText
}

Thus, the ViewModel does not know about the View directly, and the View reacts to data changes, ensuring loose coupling and ease of testing.