Junior — Middle
Explain the working principle of the MVVM architectural pattern and its components.
sobes.tech AI
Answer from AI
MVVM (Model-View-ViewModel) is an architectural pattern that separates the application logic into three components:
-
Model — data model and business logic. Responsible for data operations, such as loading from a network or database.
-
View — user interface that displays data and accepts user actions.
-
ViewModel — intermediary between Model and View. Contains presentation logic, transforms data from the model into a format suitable for display, and handles user commands.
Working principle:
- The View subscribes to changes in the ViewModel (e.g., through bindings or observers).
- The ViewModel requests data from the Model and updates its state.
- When data changes, the ViewModel notifies the View, which updates the interface.
This separation simplifies testing and maintaining the code, as UI and business logic are separated.
Example in Swift using Combine:
class ViewModel: ObservableObject {
@Published var text: String = ""
func fetchData() {
// load data and update text
text = "Data loaded"
}
}
// The View subscribes to ViewModel changes and updates UI automatically