Kotlin · Module 7 · Lesson 21 min read

State, Lists & ViewModel

State drives the UI

kotlin
var count by remember { mutableStateOf(0) }
Button(onClick = { count++ }) { Text("Clicked $count times") }
  • mutableStateOf holds a value that Compose watches.
  • remember keeps it across recompositions (redraws).
  • rememberSaveable also survives rotation. When the state changes, Compose redraws only what's affected.

State hoisting

Keep composables stateless where possible: pass the value down and events up.

kotlin
@Composable
fun Counter(count: Int, onIncrement: () -> Unit) { … }

This makes them reusable, testable and previewable.

Efficient lists: LazyColumn

kotlin
LazyColumn {
    items(todos, key = { it.id }) { todo -> TodoRow(todo) }
}

Only visible rows are built, like RecyclerView with far less code. Provide stable keys.

scss
UI (Compose) ← observes state ← ViewModel ← Repository ← API / Room database
UI → sends events (clicks)  →  ViewModel
  • The ViewModel exposes StateFlow<UiState>; the UI collects it with collectAsStateWithLifecycle().
  • The ViewModel launches coroutines in viewModelScope (cancelled automatically).
  • The UI never talks to the network directly.

Common libraries

Retrofit or Ktor (networking), Room (local database), Hilt (dependency injection), Coil (images), Navigation Compose (screens), DataStore (settings).

Example

kotlin
// TodoScreen.kt — Compose + ViewModel + StateFlow (Android Studio project)
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update

data class Todo(val id: Int, val text: String, val done: Boolean = false)

class TodoViewModel : ViewModel() {
    private val _todos = MutableStateFlow(listOf(Todo(1, "Learn Kotlin"), Todo(2, "Try Compose")))
    val todos: StateFlow<List<Todo>> = _todos
    private var nextId = 3

    fun add(text: String) {
        if (text.isBlank()) return
        _todos.update { it + Todo(nextId++, text.trim()) }
    }
    fun toggle(id: Int) = _todos.update { list ->
        list.map { if (it.id == id) it.copy(done = !it.done) else it }
    }
}

@Composable
fun TodoScreen(vm: TodoViewModel = viewModel()) {
    val todos by vm.todos.collectAsStateWithLifecycle()
    var input by rememberSaveable { mutableStateOf("") }

    Column(Modifier.padding(16.dp)) {
        Row {
            OutlinedTextField(input, { input = it }, Modifier.weight(1f), label = { Text("New task") })
            Spacer(Modifier.width(8.dp))
            Button(onClick = { vm.add(input); input = "" }) { Text("Add") }
        }
        Text("${todos.count { !it.done }} left", Modifier.padding(vertical = 8.dp))
        LazyColumn {
            items(todos, key = { it.id }) { todo ->
                Row(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
                    Checkbox(checked = todo.done, onCheckedChange = { vm.toggle(todo.id) })
                    Text(todo.text, Modifier.padding(top = 12.dp))
                }
            }
        }
    }
}
// 💻 Run in Android Studio. Needs lifecycle-viewmodel-compose and lifecycle-runtime-compose