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.
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:
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
- (docs)
Layoutgives youmeasurables(the children) and the incomingconstraints. Each child is measured once, then placed. - (docs)
placeRelativeflips for right-to-left languages;placedoes not. PreferplaceRelativeunless you want a fixed side. - (general knowledge) The
coerceIncalls 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.layoutor aLayoutModifierNodeoverSubcomposeLayoutorBoxWithConstraints, 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 disappearing | AnimatedVisibility (enter and exit transitions) |
| A change of size | Modifier.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 layouts | Crossfade; for more than a fade, AnimatedContent |
(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:
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:
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 newercomputedStateOfis now recommended for most cases, withderivedStateOfkept 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 arememberkey, which recreates the block on every change.keyandcontentType(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
- 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.
- (docs) Flat data classes with
valproperties of primitive or String types are inferred stable, so adding@Immutableis redundant.@Stableor@Immutableis 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
(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.
Try It Yourself
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.
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.
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 solutionmeasure, 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).