The old Android toolkit was imperative: you inflated an XML layout, found a view by its id, and called setter methods on it to change it. Keeping that mutable widget tree in agreement with your data was the source of an enormous number of bugs.
Compose inverts this. A composable function takes data and emits UI. It returns Unit - it describes rather than builds - and it is annotated @Composable. When the data changes, the framework calls the function again and works out the minimal set of changes to apply. That re-execution is called recomposition, and it is the one concept that makes everything else make sense.
Because composables are just functions, composition is function calls, reuse is extracting a function, and conditional UI is an ordinary if. There is no XML, no inflation step and no findViewById.
Two rules keep recomposition safe. A composable must be side-effect free, because it may be called often, in any order, or skipped entirely. And anything that must happen once - starting a network call, showing a snackbar - belongs in a dedicated effect such as LaunchedEffect, not in the composable body. The @Preview annotation renders a composable in the IDE without running the app, which makes iterating on layout fast.
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
data class Note(val title: String, val done: Boolean)
// A composable takes data and emits UI. It returns nothing.
@Composable
fun NoteRow(note: Note, onToggle: () -> Unit) {
Row(
modifier = Modifier.fillMaxWidth().padding(16.dp),
verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
) {
Checkbox(checked = note.done, onCheckedChange = { onToggle() })
Spacer(Modifier.width(12.dp))
Text(text = note.title, style = MaterialTheme.typography.bodyLarge)
}
}
// Reuse is just calling the function again
@Composable
fun NoteList(notes: List<Note>, onToggle: (Int) -> Unit) {
Column {
notes.forEachIndexed { index, note ->
NoteRow(note = note) { onToggle(index) }
}
}
}
@Preview
@Composable
fun NoteListPreview() {
MaterialTheme {
NoteList(listOf(Note("Buy milk", false), Note("Call Ada", true))) { }
}
}
Discussion
No questions on this topic yet. Sign in to ask the first one.