Junior — Middle
What is the difference in the ways of communication between View and its models: ViewModel and View, as well as Presenter and View?
sobes.tech AI
Answer from AI
In Android architecture, the relationship between View and its models (ViewModel and Presenter) differs in the way they interact and their responsibilities:
-
View and ViewModel (MVVM)
- ViewModel does not contain references to View, ensuring loose coupling.
- ViewModel provides data through Observable objects (e.g., LiveData), which View subscribes to.
- Changes in data are automatically reflected in View through observers.
- ViewModel does not know about the specific implementation of View, which facilitates testing.
-
Presenter and View (MVP)
- Presenter has a reference to View through an interface.
- View calls methods on Presenter, and Presenter directly updates View through the interface.
- The connection is more rigid, with Presenter managing the display logic.
Example:
MVVM:
viewModel.data.observe(this) { data ->
view.update(data)
}
MVP:
interface View {
fun showData(data: String)
}
class Presenter(val view: View) {
fun loadData() {
val data = "..."
view.showData(data)
}
}
Thus, MVVM is oriented towards reactive updates via observers, while MVP focuses on direct control of View through the Presenter interface.