Advanced Compose

Android Development with Compose: Production & Publishing

Course 6 ยท Chapter 1 ยท Beyond the Basics

The notes app from Android Development with Compose: Architecture & Data works, but a production app is judged on how it feels: smooth, responsive, consistent. This chapter covers the Compose tools for that: building your own modifiers and layouts, animating changes, and keeping recomposition cheap.

What was checked, and how: read this first
Checked in the docs (three searches, summaries only): Layout: parents pass constraints down and children report a size within them; the layout modifier gives you a measurable and the constraints, measurable.measure(constraints) makes a placeable, and layout(width, height) { ... } sets the size and holds the placement; the Layout composable gives measurables and constraints; placeRelative follows the layout direction and place does not; placing is only allowed after measuring, inside the layout pass; and for constraint-dependent measuring the docs prefer Modifier.layout or a LayoutModifierNode over SubcomposeLayout or BoxWithConstraints. Animation: the four tools and the "Choose an animation API" guidance below, including that animateContentSize goes before the size modifiers. Performance: defer state reads to layout or draw with lambda modifiers such as Modifier.offset { ... }; never write state that was already read in the same composition; give lazy layouts stable keys and content types; flat data classes with val primitive or String properties are inferred stable so @Immutable is redundant; skipping is not free; keep a list's instance when its content has not changed; measure with benchmarks, not recomposition counts alone; and, from one result, a newer computedStateOf that the docs now recommend over derivedStateOf for most cases (introduced in a Compose 1.13 release; I did not confirm its signature, so the code below uses the long-established derivedStateOf). General knowledge, not checked: the custom-modifier extension and Layout code as written, the ExpandableNote and scroll-to-top composables, the theme extension, "strong skipping" as a compiler default, and the Layout Inspector remarks. Theming was not searched in this chapter; Android Development Fundamentals with Compose 8 has the checked material. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.

Custom Modifiers

(docs) The layout modifier lets you change how one element is measured and placed. You measure the wrapped element, report a size, and place it:

import androidx.compose.ui.Modifier import androidx.compose.ui.layout.layout import androidx.compose.ui.unit.Dp // A custom modifier: add space above the first line of content fun Modifier.paddingFromTop(top: Dp) = layout { measurable, constraints -> val placeable = measurable.measure(constraints) // 1. measure the wrapped element val extra = top.roundToPx() layout(placeable.width, placeable.height + extra) { // 2. report a size placeable.placeRelative(x = 0, y = extra) // 3. place it } }

The three steps are always the same: measure the child with the incoming constraints, report your own size with layout(width, height), then place the child in the placement block. (docs) Placing is only allowed in that block, after measuring. (general knowledge) A modifier that only combines existing modifiers can be an ordinary extension function that returns this.padding(...).background(...) without any measuring.

A Custom Layout

import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.Layout // A custom layout: children stacked vertically, like a simple Column @Composable fun SimpleColumn(modifier: Modifier = Modifier, content: @Composable () -> Unit) { Layout(content = content, modifier = modifier) { measurables, constraints -> val placeables = measurables.map { it.measure(constraints) } val width = (placeables.maxOfOrNull { it.width } ?: 0) .coerceIn(constraints.minWidth, constraints.maxWidth) val height = placeables.sumOf { it.height } .coerceIn(constraints.minHeight, constraints.maxHeight) layout(width, height) { var y = 0 placeables.forEach { placeable -> placeable.placeRelative(x = 0, y = y) y += placeable.height } } } }
  • (docs) Layout gives you measurables (the children) and the incoming constraints. Each child is measured once, then placed.
  • (docs) placeRelative flips for right-to-left languages; place does not. Prefer placeRelative unless you want a fixed side.
  • (general knowledge) The coerceIn calls keep the reported size inside the constraints; a layout that reports an impossible size is a bug.
  • (docs) When measurement depends on constraints, the performance guidance prefers Modifier.layout or a LayoutModifierNode over SubcomposeLayout or BoxWithConstraints, which do more work.

You rarely need your own layout: Column, Row, Box and LazyColumn cover most screens. Write one when no built-in arrangement matches, for example a flow of tags that wraps, or a layout that overlaps children in an unusual way.

Animation: Choosing the Right Tool

You want to animate…Use (docs)
A composable appearing or disappearingAnimatedVisibility (enter and exit transitions)
A change of sizeModifier.animateContentSize(), placed before size modifiers
One independent value (alpha, offset, padding, colour)An animate*AsState function: you give the target, it animates from the current value, and adjusts if the target changes mid-way
Swapping between two layoutsCrossfade; for more than a fade, AnimatedContent
// One value, animated: you give the target and the state follows it val alpha by animateFloatAsState( targetValue = if (enabled) 1f else 0.4f, label = "alpha" ) Text("Sync", modifier = Modifier.alpha(alpha))

(docs) One difference to know: animating alpha with animateFloatAsState can leave an invisible item in the accessibility tree, whereas AnimatedVisibility eventually removes it from the composition. For something that should really go away, use AnimatedVisibility.

Putting It In the Notes App

An expandable note card, using animateContentSize:

import androidx.compose.animation.animateContentSize import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Card import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @Composable fun ExpandableNote(text: String, modifier: Modifier = Modifier) { var expanded by rememberSaveable { mutableStateOf(false) } Card( modifier = modifier .animateContentSize() // before the size modifiers, per the docs .fillMaxWidth() .clickable { expanded = !expanded } ) { Text( text = text, maxLines = if (expanded) Int.MAX_VALUE else 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(16.dp) ) } }

A scroll-to-top button, using AnimatedVisibility and derivedStateOf, in the shape the docs use as their own example, together with stable keys and content types for the lazy list:

import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.runtime.* import kotlinx.coroutines.launch @Composable fun NotesList(notes: List<Note>) { val listState = rememberLazyListState() val scope = rememberCoroutineScope() // Recomputes only when the answer changes, not on every scroll pixel val showScrollToTop by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } } Box { LazyColumn(state = listState) { items(notes, key = { it.id }, contentType = { "note" }) { note -> ExpandableNote(text = note.text) } } AnimatedVisibility(visible = showScrollToTop, modifier = Modifier.align(Alignment.BottomEnd)) { FloatingActionButton(onClick = { scope.launch { listState.animateScrollToItem(0) } }) { Icon(Icons.Filled.KeyboardArrowUp, contentDescription = "Scroll to top") } } } }
  • derivedStateOf (docs) turns a fast-changing value (the scroll position) into a value that changes rarely (is the button needed?), so the composable only recomposes when the answer changes. (docs) The newer computedStateOf is now recommended for most cases, with derivedStateOf kept for heavy calculations read several times per pass. Check your Compose version and the current docs. A common mistake the docs warn about is passing the state you read as a remember key, which recreates the block on every change.
  • key and contentType (docs) in the lazy list let it skip work and reuse slots. Here the note's id is the key (it is unique and stable).

Keeping Recomposition Cheap

// Reads state during composition: the whole composable recomposes on every change Box(Modifier.offset(x = scrollOffset.dp)) // Reads state in the layout phase: only layout reruns, composition is skipped Box(Modifier.offset { IntOffset(x = scrollOffset, y = 0) })
  • Defer reads. (docs) Compose works in phases: composition, layout, draw. A lambda modifier such as Modifier.offset { ... } reads the state later, in the layout phase, so a value that changes every frame no longer re-runs composition.
  • No backwards writes. (docs) Never write to state that has already been read in the same composable's composition; it causes extra recompositions.
  • Stability. (docs) Compose can skip a composable whose inputs have not changed.
// Stable by inference (docs): all val properties, primitive or String types. @Immutable would be redundant. data class Note(val id: Long, val text: String, val createdAt: Long) // A list parameter: keep the same list instance when the content has not changed @Composable fun NotesList(notes: List<Note>) { /* ... */ }
  • (docs) Flat data classes with val properties of primitive or String types are inferred stable, so adding @Immutable is redundant. @Stable or @Immutable is worth it only in narrow cases, such as classes from non-Compose modules.
  • (docs) Skipping is not free: each parameter of a skippable composable is stored as if remembered, so do not try to force skipping everywhere.
  • (docs) For collections, keep the list instance the same when its content has not changed; reach for an immutable-list type only if a benchmark justifies it.
  • (general knowledge, not checked) Recent Compose compilers skip more composables by default ("strong skipping"); the Compose compiler's stability reports show what the compiler decided for your classes.
  • (docs) Measure. Do not judge performance by recomposition counts alone; use benchmarks (Chapter 6 of this course returns to measuring).

Extending the Theme

import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp // Extending the theme with your own tokens data class Spacing(val small: Dp = 8.dp, val medium: Dp = 16.dp, val large: Dp = 24.dp) val LocalSpacing = staticCompositionLocalOf { Spacing() } @Composable fun NotesTheme(content: @Composable () -> Unit) { CompositionLocalProvider(LocalSpacing provides Spacing()) { MaterialTheme(content = content) // colour scheme, typography, shapes as in Fundamentals 8 } } // Use it: Modifier.padding(LocalSpacing.current.medium)

(general knowledge, not checked in this chapter) A theme is more than colours: a CompositionLocal lets you add your own tokens (spacing, elevations) that any composable below can read, without passing them as parameters. Colour schemes, dark theme and dynamic colour are covered, from checked sources, in Android Development Fundamentals with Compose 8.

Compared with the Classic UI course
Android Development: Production & Publishing 1 teaches Jetpack Compose Advanced: custom layouts, animations, theming and performance. The topics are the same; this edition adds the docs' current performance guidance (deferred reads, stability inference, benchmarks over recomposition counts) and the animation-API decision guide.

Try It Yourself

Exercise 1

Write paddingFromTop and SimpleColumn, then preview SimpleColumn with three text children, once alone and once inside a Box with a narrow width. Report how it behaves when the constraints are tight, and what happens if you remove the coerceIn calls.

๐Ÿ“„ View solution
Exercise 2

Add ExpandableNote and the scroll-to-top button to the notes app. Test with at least 40 notes. Then check your Compose version, look up computedStateOf in the current docs, and say whether it applies to you.

๐Ÿ“„ View solution
Exercise 3

Find one value in your app that changes often (for example an animated offset) and move its read into a lambda modifier. Explain why this skips composition, then say which tools you would use to confirm the change helped, and why recomposition counts alone are not enough.

๐Ÿ“„ View solution
Not Yet Verified
Checked in the docs (three searches, summaries only): constraints, measure, layout(width, height) and placement; Layout's measurables; placeRelative against place; placing only in the layout pass; the preference for Modifier.layout or LayoutModifierNode over SubcomposeLayout and BoxWithConstraints; the animation tools, the choice guidance, the alpha and accessibility-tree note and animateContentSize placement; deferred state reads; backwards writes; stable keys and content types; stability inference and @Immutable redundancy; skipping not being free; list instances; measuring over counting; the computedStateOf recommendation.
General knowledge, not checked: the code as written (including every import and the roundToPx call); the custom-modifier-by-composition remark; strong skipping as a compiler default; the Compose compiler stability reports; the CompositionLocal theme extension and the idea that a theme is more than colours.
Not verified: the computedStateOf signature and the Compose version that introduced it; every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: Custom layouts (developer.android.com), Create custom modifiers (developer.android.com), Quick guide to Animations in Compose (developer.android.com), Choose an animation API (developer.android.com), Follow best practices (developer.android.com), Fix stability issues (developer.android.com), Modifier breakdown by phase (developer.android.com).
Coming up
Chapter 2 is Testing, which the previous course kept promising: the DAO, ViewModel and serialization tests done properly, Compose UI tests, and a Room migration test.