Describe MVVM.
Tier: EssentialDifficulty: Easy
MVVM splits an app into three layers, Model, View, and ViewModel, so the UI and the business logic don't end up tangled together in the same class.
The Model handles data and business logic, repositories, local and remote data sources, and plain data classes. The View is the UI layer, an Activity, Fragment, or composable, and its only job is to render whatever state it's given and forward user actions onward. The ViewModel sits between the two, it pulls data from the Model, turns it into UI ready state, and exposes that state through something observable like StateFlow or LiveData.
class UserViewModel(private val repo: UserRepository) : ViewModel() {
private val _user = MutableStateFlow<User?>(null)
val user: StateFlow<User?> = _user
fun loadUser(id: String) {
viewModelScope.launch { _user.value = repo.getUser(id) }
}
}
The key detail that makes MVVM work is that the ViewModel has no reference to the View at all, it doesn't hold an Activity, a Fragment, or a Context. The View observes the ViewModel and updates itself, but the ViewModel never reaches back to touch the View directly. That one way relationship is what makes the ViewModel testable on its own and what lets it survive configuration changes without dragging a dead View reference along with it.