Skip to the workspace
Pebellslearn by building
Building Screens with Jetpack Compose  ›  Lesson

Jetpack Compose — UI as Functions

Jetpack Compose 14 minIn Jetpack Compose, UI is described by composable functions that turn state into what is on screen, and Compose redraws the affected parts when that state changes.

android / Jetpack Compose — UI as Functions

Explore each scene at your own pace.

01 · The rule

The rule

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) }
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.