App Architecture: MVVM, ViewModel & Flow
Why architecture matters
Putting all code in the Activity leads to bugs and crashes on rotation. The recommended pattern is MVVM: Model (data), View (UI), ViewModel (state + logic).
ViewModel survives rotation
class UserViewModel : ViewModel() {
private val _name = MutableStateFlow("")
val name: StateFlow<String> = _name
fun load() {
viewModelScope.launch {
_name.value = "Anand" // from a repository in real apps
}
}
}
Observe state in the Activity
lifecycleScope.launch {
viewModel.name.collect { value ->
binding.name.text = value
}
}
Layers: UI → ViewModel → Repository → (Room + Retrofit). Each layer has one job, which makes the app easy to test and grow.