Jetpack Compose — UI as Functions
In older Android code, updating Sprout's "watered 3 times" label meant finding the label view and changing its text by hand. Forget one update and the screen lies. Jetpack Compose removes that whole class of bug by flipping the approach: you describe what the screen should look like, and Compose keeps it in sync.
The rule
UI is a function of state; change the state, not the screen.
A composable is a Kotlin function marked @Composable that describes part of the UI:
@Composable
fun WateringCount(count: Int) {
Text(text = "Watered $count times")
}Key facts:
- Composables emit UI; they do not return views. Their return type is
Unit. - By convention, their names are PascalCase nouns, like
PlantCard, because they read like UI elements. - They can only be called from other composables, or from
setContent. - When state a composable reads changes, Compose calls it again. This is recomposition, and Compose only reruns the parts that depend on the changed state.
Because a composable may run many times, and in any order, it must be free of side effects: no saving files or starting network calls inside it.
@Preview lets you see a composable in Android Studio without running the app:
@Preview
@Composable
fun WateringCountPreview() { WateringCount(count = 3) }