Level 6
ViewModel & Flow (Architecture)
MVVM with StateFlow
Business logic lives in the `ViewModel`. The UI observes `StateFlow`. This survives configuration changes (rotation).
📚 Explanation
ViewModel holds business logic and survives configuration changes. `StateFlow` is a hot flow that emits the current state to collectors. `collectAsStateWithLifecycle` automatically stops collecting when the lifecycle is destroyed, preventing leaks.
Note: Code execution is not available for Android/Kotlin in the browser. Use Android Studio to run and test the app.
import androidx.lifecycle.ViewModelimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.flow.update// 1. The Logicclass UserViewModel : ViewModel() {// Private mutable stateprivate val _uiState = MutableStateFlow(UserUiState())// Public read-only stateval uiState = _uiState.asStateFlow()fun loadData() {_uiState.update { it.copy(isLoading = true) }// ... async work ..._uiState.update { it.copy(isLoading = false, name = "Cristian") }}}data class UserUiState(val name: String = "", val isLoading: Boolean = false)// 2. The UI consumption@Composablefun UserScreen(viewModel: UserViewModel = androidx.lifecycle.viewmodel.compose.viewModel()) {// "collectAsStateWithLifecycle" is the safest way to collect flows in UIval state by viewModel.uiState.collectAsStateWithLifecycle()if (state.isLoading) {CircularProgressIndicator()} else {Text("Welcome, ${state.name}")}}