Kotlin

ViewModel + StateFlow + Compose

admin by @admin ADMIN
4m ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Standard Android pattern: ViewModel holds state in a `StateFlow`, Compose collects it as state. Survives config changes; isolates business logic from UI.
Kotlin
Raw
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import androidx.compose.runtime.*
import androidx.compose.material3.Text

data class CounterUiState(val count: Int = 0, val loading: Boolean = false)

class CounterViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(CounterUiState())
    val uiState: StateFlow<CounterUiState> = _uiState.asStateFlow()

    fun increment() {
        _uiState.update { it.copy(count = it.count + 1) }
    }

    fun loadFromNetwork() {
        viewModelScope.launch {
            _uiState.update { it.copy(loading = true) }
            kotlinx.coroutines.delay(500)
            _uiState.update { it.copy(count = 42, loading = false) }
        }
    }
}

@Composable
fun CounterScreen(vm: CounterViewModel) {
    val state by vm.uiState.collectAsState()       // lifecycle-aware collect
    Text("count: ${state.count}, loading: ${state.loading}")
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.