Junior — Middle
Can you explain the main principles and components of the MVVM architectural pattern?
sobes.tech AI
Answer from AI
MVVM (Model-View-ViewModel) — an architectural pattern that divides application logic into three components:
- Model — responsible for data and business logic. These can be objects working with network, database, etc.
- View — displays data to the user and handles user input. In Android, this is usually an Activity or Fragment.
- ViewModel — an intermediary between Model and View. It receives data from the Model, transforms it into a display-friendly format, and provides it to the View. It also handles user actions, passing them to the Model.
Main principles:
- Separation of UI from business logic for better testability and maintainability.
- ViewModel does not contain references to the View, allowing easy UI changes.
- Use of observable data (LiveData, Flow) to update the View when data changes.
Example in Kotlin with LiveData:
class MyViewModel : ViewModel() {
private val _data = MutableLiveData<String>()
val data: LiveData<String> = _data
fun loadData() {
// Get data from Model
_data.value = "Hello, MVVM!"
}
}
// In Activity
viewModel.data.observe(this) { value ->
textView.text = value
}