← All courses

App Architecture: MVVM, ViewModel & Flow

🗓 May 31, 2026 ⏱ 1 min read

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).

View (UI) ViewModel Repository

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.