Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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) }

The shortcut

For any UI change, ask "what state changed?" Update that; never reach into the screen.

The user taps "Water" in SproutStep 1 of 4
  1. Old habit

    Find the label, call setText. Compose has no such step.

Drills

Answer fast — trust the rule.

quick drill

What marks a Kotlin function as a composable?

quick drill

In Compose, how do you make a label show a new value?

quick drill

What is recomposition?

quick drill

Why should a composable not save data to a database directly in its body?

Remember

  • UI is a function of state; change the state, not the screen.
  • Composables are @Composable, return Unit, and are named like UI elements.
  • Recomposition can happen often, so keep composable bodies free of side effects.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainDescribe, don't change

In the old View system, you would find Sprout's counter label and call setText when the user waters a plant. Explain how the same feature works in Compose, and what recomposition does.