ViewModel and UI State with StateFlow
Why ViewModel?
- A ViewModel survives rotation and other configuration changes, while the Activity is recreated
- It keeps screen logic and data outside composables
- It is easy to unit test
- It cancels its coroutines automatically in
onCleared
Step 1: Add the Library
kotlin
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.lifecycle.runtime.compose)
Step 2: UI State and ViewModel
kotlin
data class TodoUiState(
val items: List<Todo> = emptyList(),
val newTitle: String = "",
val isLoading: Boolean = false,
val error: String? = null
) {
val remaining: Int get() = items.count { !it.done }
}
data class Todo(val id: Int, val title: String, val done: Boolean = false)
class TodoViewModel : ViewModel() {
private val _uiState = MutableStateFlow(TodoUiState())
val uiState: StateFlow<TodoUiState> = _uiState.asStateFlow()
private var nextId = 1
fun onTitleChange(value: String) = _uiState.update { it.copy(newTitle = value) }
fun add() {
val title = _uiState.value.newTitle.trim()
if (title.isEmpty()) return
_uiState.update {
it.copy(items = it.items + Todo(nextId++, title), newTitle = "")
}
}
fun toggle(id: Int) = _uiState.update { state ->
state.copy(items = state.items.map { if (it.id == id) it.copy(done = !it.done) else it })
}
fun delete(id: Int) = _uiState.update { state ->
state.copy(items = state.items.filterNot { it.id == id })
}
}
Step 3: The Screen
kotlin
@Composable
fun TodoScreen(viewModel: TodoViewModel = viewModel()) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
Column(Modifier.padding(16.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(
value = state.newTitle,
onValueChange = viewModel::onTitleChange,
label = { Text("New task") },
modifier = Modifier.weight(1f)
)
Spacer(Modifier.width(8.dp))
Button(onClick = viewModel::add) { Text("Add") }
}
Text("${state.remaining} remaining", Modifier.padding(vertical = 8.dp))
LazyColumn {
items(state.items, key = { it.id }) { todo ->
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(todo.done, onCheckedChange = { viewModel.toggle(todo.id) })
Text(todo.title, Modifier.weight(1f))
IconButton(onClick = { viewModel.delete(todo.id) }) { Icon(Icons.Default.Delete, "Delete") }
}
}
}
}
}
Rotate the phone: The list and text survive rotation, because the ViewModel instance is kept. Plain
remember state would be lost.
One-time Events
kotlin
sealed interface TodoEvent { data class ShowMessage(val text: String) : TodoEvent }
private val _events = Channel<TodoEvent>(Channel.BUFFERED)
val events = _events.receiveAsFlow()
// in the screen
LaunchedEffect(Unit) {
viewModel.events.collect { if (it is TodoEvent.ShowMessage) snackbarHostState.showSnackbar(it.text) }
}
SavedStateHandle
A ViewModel is destroyed if Android kills the app process in the background. Use SavedStateHandle for small values you must restore.
kotlin
class SearchViewModel(private val savedState: SavedStateHandle) : ViewModel() {
val query = savedState.getStateFlow("query", "")
fun onQueryChange(value: String) { savedState["query"] = value }
}
Rules: Never pass a Context or a composable into a ViewModel. Expose
StateFlow, not MutableStateFlow. Update state with copy and update.
Conclusion
The ViewModel holds UI state in a StateFlow and receives events from the screen. The screen collects state in a lifecycle-aware way.
Quick Summary: UiState data class, MutableStateFlow in the ViewModel, collectAsStateWithLifecycle in Compose and viewModelScope for work.

