Sobes.tech
Junior — Middle

How can you notify the View about data changes in the MVVM architecture?

sobes.tech AI

Answer from AI

In the MVVM architecture, the notification to the View about data changes is usually achieved through a change observation mechanism in the ViewModel. In Android, this is often implemented using:

  • LiveData — an object that holds data and notifies subscribers (the View) when it changes.
  • StateFlow / Flow from Kotlin Coroutines — reactive data streams that the View can observe.

Example with LiveData:

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

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

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

Thus, when data in the ViewModel changes, the View automatically receives a notification and updates the UI.

How can you notify the View about data changes in the… - sobes.tech