Junior — Middle
What methods are used for data exchange between ViewModel and View in MVVM architecture?
sobes.tech AI
Answer from AI
In MVVM architecture, data exchange between ViewModel and View is usually carried out through the following methods:
-
Observables: The View subscribes to data changes in the ViewModel. In Android, LiveData or StateFlow are often used, which notify the View of changes.
-
Data Binding: Allows automatic binding of ViewModel properties to UI elements in the View, updating the UI when data changes.
-
Events: The ViewModel can send events (e.g., via SingleLiveEvent or channels) so that the View reacts to one-time actions such as navigation or message display.
Example with LiveData:
class MyViewModel : ViewModel() {
val data = MutableLiveData<String>()
fun loadData() {
data.value = "Hello, MVVM!"
}
}
// In Activity or Fragment
viewModel.data.observe(viewLifecycleOwner) { value ->
textView.text = value
}
Thus, the ViewModel does not know about the View directly, and the View reacts to data changes, ensuring loose coupling and ease of testing.