Jetpack Compose in 2026: State, Navigation, Performance and Architecture
Derar SattoufUpdated Mobile

Jetpack Compose is the default UI toolkit for Android. The early arguments are over: the question is not whether to use it but how to use it well. Teams that struggle with Compose almost never struggle with the syntax. They struggle with state that lives in the wrong place, lists that recompose more than they should, navigation that grows into a tangle, and release builds that are slower than debug builds felt, because nobody configured a Baseline Profile.
Hoist state. Composables should be stateless where possible: take a value and an event lambda, and let a caller own the state. Keep a screen's UI state in a ViewModel exposed as StateFlow, collected with collectAsStateWithLifecycle(). State flows down and events flow up, with a single immutable UiState per screen and one-shot effects modelled as state or a channel used with care. Use remember for in-composition caching and rememberSaveable for state that must survive recreation, and reach for derivedStateOf only when an input changes more often than the output you care about.
Strong skipping mode is on by default with current Kotlin and the Compose compiler plugin, which makes most composables skippable even with unstable parameters. You still need stable types and lambdas in hot paths, and you should check the compiler reports rather than assume. Always give lazy list items stable keys and a contentType, and keep per-item work out of composition.
For navigation, Navigation Compose with type-safe @Serializable routes is established, and Navigation 3 (stable since late 2025) gives you an explicit back stack you own. Pick one deliberately per app. Ship a Baseline Profile: it's the cheapest large startup and jank improvement available, and you measure it with Macrobenchmark on a release-like build with R8 enabled. Test at three levels (ViewModel unit tests, Compose UI tests with semantics, and screenshot tests with Paparazzi, Roborazzi or the Compose Preview Screenshot Testing tooling), and build adaptive, using window size classes and the adaptive libraries so your app works on phones, foldables, tablets and desktop windowing.
Versions move fast. Compose ships on a regular cadence through the Compose BOM, Navigation 3 reached stable in late 2025, and AndroidX libraries add APIs constantly. Where a version or signature matters, the text says so and points you to the current docs. Prefer the BOM to pinning individual Compose artifact versions, and check the release notes page of each library before copying a dependency line.
How Compose actually works
Compose has three phases per frame: composition (run composable functions to build a tree of what to show), layout (measure and place), and drawing. State reads are tracked: when a composable reads a State value during composition, Compose records that read. When the value changes, only the scopes that read it are scheduled for recomposition. Compose can skip a composable if all of its inputs are unchanged and it is considered skippable.
Three practical consequences:
- Composable functions can run often, in any order, and sometimes in parallel in the future. They must be fast and free of side effects. Side effects belong in effect handlers (
LaunchedEffect,DisposableEffect,SideEffect). - Where you read state decides what recomposes. Reading a rapidly changing value high in the tree recomposes a lot; reading it lazily in a lower phase (layout or draw) recomposes nothing.
- Stability decides whether skipping works. If Compose cannot tell that a parameter is unchanged, it recomposes the function.
State change
│
▼
Composition ──(only scopes that read the state)──► new UI tree
│
▼
Layout ──(skipped if only drawing changed)──► sizes and positions
│
▼
Drawing ──► pixelsOptimisations in Compose follow one principle: defer reads to the latest phase that needs them. A lambda-based modifier such as Modifier.offset { IntOffset(x, 0) } reads state during layout instead of composition. Modifier.graphicsLayer { alpha = a } and drawBehind read in the draw phase.
State: remember, rememberSaveable, hoisting
The state vocabulary
| Tool | Survives recomposition | Survives config change / process death | Use for |
|---|---|---|---|
Plain var in a composable | No (resets) | No | Never for UI state |
remember { mutableStateOf(x) } | Yes | No | Ephemeral UI state, such as an expanded flag |
rememberSaveable { mutableStateOf(x) } | Yes | Yes, for types saveable in a Bundle or with a custom Saver | Text input, scroll positions, selected tabs |
ViewModel state | Yes | Survives configuration change; use SavedStateHandle for process death | Screen state tied to business logic |
| Persistent storage (Room, DataStore) | Yes | Yes | Real data |
@Composable
fun ExpandableCard(title: String, details: String) {
var expanded by rememberSaveable { mutableStateOf(false) }
Card(onClick = { expanded = !expanded }) {
Column(Modifier.padding(16.dp)) {
Text(title, style = MaterialTheme.typography.titleMedium)
AnimatedVisibility(expanded) {
Text(details, style = MaterialTheme.typography.bodyMedium)
}
}
}
}State hoisting
Hoisting means moving state up to the caller and passing down a value plus an event callback. A hoisted composable is easier to test, preview and reuse because it has no hidden state.
// Stateless: the caller owns the value
@Composable
fun SearchField(
query: String,
onQueryChange: (String) -> Unit,
modifier: Modifier = Modifier,
) {
OutlinedTextField(
value = query,
onValueChange = onQueryChange,
modifier = modifier,
singleLine = true,
label = { Text("Search") },
leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
)
}Where to hoist to: the lowest common ancestor that needs to read or write the state. UI element state (scroll, animation) hoists into a plain state holder class; business state hoists into a ViewModel.
Plain state holder classes
When a composable accumulates several related pieces of UI state and logic (but no business logic), extract a state holder created with remember.
@Stable
class FormState(initialName: String = "") {
var name by mutableStateOf(initialName)
var showErrors by mutableStateOf(false)
val nameError: String?
get() = if (name.isBlank()) "Name is required" else null
val isValid: Boolean get() = nameError == null
companion object {
val Saver: Saver<FormState, String> = Saver(
save = { it.name },
restore = { FormState(it) },
)
}
}
@Composable
fun rememberFormState(): FormState =
rememberSaveable(saver = FormState.Saver) { FormState() }derivedStateOf
Use derivedStateOf when you derive a value from state that changes more often than the derived result changes. The classic case is "show the scroll-to-top button once the first visible item is past zero".
val listState = rememberLazyListState()
val showButton by remember {
derivedStateOf { listState.firstVisibleItemIndex > 0 }
}Without derivedStateOf, reading listState.firstVisibleItemIndex directly in composition would recompose on every index change. Do not use it to wrap trivial transformations where the output changes as often as the input; it adds overhead for no gain. Do not use it to combine two states into one when both change together.
rememberSaveable pitfalls
- Objects that are not Bundle-compatible need a
Saver(or uselistSaver/mapSaver) or must beParcelableorSerializable. - Large data in saved state risks
TransactionTooLargeException. Save identifiers and re-derive. rememberwith keys:remember(userId) { ... }recomputes whenuserIdchanges. Forgetting keys is a common source of stale values.
Effects
| Effect | Use |
|---|---|
LaunchedEffect(key) | Run a suspend block when entering composition or when key changes; cancelled on leave |
rememberCoroutineScope() | Launch coroutines from event handlers such as clicks |
DisposableEffect(key) | Register and unregister listeners; must implement onDispose |
SideEffect | Publish Compose state to non-Compose code every successful recomposition |
produceState | Convert non-Compose async sources into State |
snapshotFlow { } | Turn Compose state reads into a Flow, for example to log scroll position |
rememberUpdatedState(x) | Capture the latest lambda or value inside a long-running effect without restarting it |
Rule: do not launch coroutines directly in the composable body. Use an effect or an event handler.
Recomposition, stability, and strong skipping
What stability means
Compose treats a type as stable if it is immutable, or if all mutations are observable by Compose (for example via MutableState). A composable whose parameters are all stable and unchanged (equals to the previous values) can be skipped.
For years, composables with unstable parameters (such as a List<T> interface from the Kotlin standard library, or a class from a module without the Compose compiler) were not skippable, which caused surprising recomposition and led to the cargo-cult of annotating everything @Immutable.
Strong skipping mode
Strong skipping mode relaxes this: composables with unstable parameters can also be skipped, comparing unstable parameters by instance equality (===) and stable parameters by equals. It also automatically remembers lambdas capturing unstable values. It became the default in the Compose compiler with Kotlin 2.0.20 and later, where the Compose compiler ships as a Kotlin compiler plugin. Verify against the current Compose compiler documentation for your Kotlin version, and note how to opt a composable out (@NonSkippableComposable) in rare cases.
What strong skipping does not solve:
- An unstable parameter that is a new instance every time (for example, a freshly created
Listor data object in the parent on each recomposition) is not equal by instance, so the child still recomposes. Pass stable or remembered instances. - Hidden instability inside lists. A
List<Item>that is rebuilt on each emission means the whole subtree recomposes; use stablekeys and immutable models, and preferkotlinx.collections.immutable(ImmutableList,PersistentList) in hot paths, or enable the stability configuration file.
The stability configuration file
Types from libraries you do not control can be declared stable in a file referenced by the compiler plugin options.
// compose_compiler_config.conf
kotlin.collections.*
kotlin.time.Duration
java.time.*
com.example.shared.model.*// build.gradle.kts (app module)
composeCompiler {
stabilityConfigurationFiles.add(
rootProject.layout.projectDirectory.file("compose_compiler_config.conf")
)
reportsDestination = layout.buildDirectory.dir("compose_compiler")
metricsDestination = layout.buildDirectory.dir("compose_compiler")
}Check the Compose compiler Gradle plugin documentation for the exact property names in your Kotlin version, since this DSL has evolved. Generate reports (they output *-classes.txt, *-composables.txt and metrics), and look for composables marked restartable but not skippable and for parameters marked unstable.
Annotations: use them deliberately
@Immutable: a promise that all public properties will never change after construction. A broken promise yields stale UI.@Stable: a promise that property changes will notify Compose, andequalsis consistent.- Do not annotate types to silence a report. Annotate types that truly meet the contract, and measure.
Practical recomposition rules
- Pass only what you need. Passing a whole
UiStateinto a leaf recomposes it for any field change. Pass the specific fields. - Use lambdas for rapidly changing values.
Modifier.offset { ... },graphicsLayer { }and passing() -> Floatinstead ofFloatdefer reads past composition. - Do not allocate in composition in hot paths: no new
List, formatters,RegexorBrushwithoutremember. - Use
keyand stable identities in loops (forloops over items inside aColumn). - Do not read state you do not need. Even a read that you ignore subscribes the scope.
- Debug with Layout Inspector's recomposition counts and the compiler reports, not intuition.
@Composable
fun ScrollingHeader(scrollOffset: () -> Int) {
// Reads state during layout, not composition.
Box(
Modifier
.fillMaxWidth()
.height(200.dp)
.offset { IntOffset(0, -scrollOffset() / 2) }
)
}Lazy lists done right
Lazy lists (LazyColumn, LazyRow, LazyVerticalGrid) compose only visible items. Most performance problems come from missing keys, heavy item composition and unstable inputs.
@Composable
fun TaskList(
tasks: List<TaskItem>,
onToggle: (Long, Boolean) -> Unit,
modifier: Modifier = Modifier,
listState: LazyListState = rememberLazyListState(),
) {
LazyColumn(modifier, state = listState, contentPadding = PaddingValues(16.dp)) {
items(
items = tasks,
key = { it.id },
contentType = { "task" },
) { task ->
TaskRow(
task = task,
onToggle = { checked -> onToggle(task.id, checked) },
modifier = Modifier.animateItem(),
)
}
}
}Rules:
- Always provide
key. Without it, item state is tied to position, so inserting at the top shifts state, scroll position jumps, and animations break. Keys must be unique and stable, and (forrememberSaveableinside items) Bundle-compatible. - Provide
contentTypefor heterogeneous lists so Compose reuses compositions of the same type. - Do not nest scrolling containers in the same direction (a
LazyColumninside averticalScrollcolumn). Use a single lazy list with multiple item groups oritem { }blocks. - Do not put the list's heavy computation in the item lambda. Precompute display strings and sort order in the ViewModel.
Modifier.animateItem()replaces the olderanimateItemPlacementfor item animations in current Compose versions; verify the name in your BOM version.- Use
LazyListStatehoisting for scroll restoration andsnapshotFlowfor analytics, rather than reading scroll offsets in composition. - Prefetching and images. Use a library such as Coil with Compose (
AsyncImage) and size images appropriately; avoid decoding full-size bitmaps for thumbnails. - Measure with a Macrobenchmark scrolling test (see the performance section) on a mid-range device.
Architecture: unidirectional data flow with ViewModel and StateFlow
Layers
┌────────────────────────────┐
│ UI (Compose) │ renders UiState, emits events
├────────────────────────────┤
│ ViewModel │ holds UiState as StateFlow, handles events
├────────────────────────────┤
│ Domain (optional use cases)│ pure Kotlin business rules
├────────────────────────────┤
│ Data (repositories) │ Room, Retrofit/Ktor, DataStore; source of truth
└────────────────────────────┘Keep the domain layer optional. For many apps, a ViewModel that talks to repositories is enough; add use cases when logic is reused across ViewModels or is complex enough to deserve isolation. This matches the guidance in the official Android architecture documentation.
UiState, events and effects
data class TaskListUiState(
val tasks: List<TaskItem> = emptyList(),
val query: String = "",
val isRefreshing: Boolean = false,
val errorMessage: String? = null,
)
sealed interface TaskListEvent {
data class QueryChanged(val query: String) : TaskListEvent
data class Toggled(val id: Long, val done: Boolean) : TaskListEvent
data object Refresh : TaskListEvent
data object ErrorShown : TaskListEvent
}Prefer modelling one-off effects (snackbars, navigation) as state that the UI consumes and acknowledges, as with errorMessage and ErrorShown above. This avoids the lost-event problems of SharedFlow and channels in the face of configuration changes. If you do use a Channel for effects, collect it with repeatOnLifecycle in a lifecycle-aware way and accept that it is a delivery-once pattern with its own edge cases.
The ViewModel
@HiltViewModel
class TaskListViewModel @Inject constructor(
private val repository: TaskRepository,
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val query = savedStateHandle.getStateFlow(KEY_QUERY, "")
private val isRefreshing = MutableStateFlow(false)
private val errorMessage = MutableStateFlow<String?>(null)
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
private val tasks: Flow<List<TaskItem>> = query
.debounce(250)
.distinctUntilChanged()
.flatMapLatest { repository.observeTasks(it) }
val uiState: StateFlow<TaskListUiState> = combine(
tasks, query, isRefreshing, errorMessage,
) { tasks, query, refreshing, error ->
TaskListUiState(tasks, query, refreshing, error)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = TaskListUiState(),
)
fun onEvent(event: TaskListEvent) {
when (event) {
is TaskListEvent.QueryChanged -> savedStateHandle[KEY_QUERY] = event.query
is TaskListEvent.Toggled -> viewModelScope.launch {
repository.setDone(event.id, event.done)
}
TaskListEvent.Refresh -> refresh()
TaskListEvent.ErrorShown -> errorMessage.value = null
}
}
private fun refresh() = viewModelScope.launch {
isRefreshing.value = true
repository.refresh().onFailure { errorMessage.value = it.message ?: "Refresh failed" }
isRefreshing.value = false
}
private companion object {
const val KEY_QUERY = "query"
}
}SharingStarted.WhileSubscribed(5_000) keeps the upstream active for five seconds after the last collector leaves, which survives configuration changes without keeping work running when the app is in the background. There is a debounce on query for the repository lookup, but the text field itself reads from uiState.query, which updates immediately; this keeps typing responsive.
Collecting state in the UI
@Composable
fun TaskListRoute(
onOpenTask: (Long) -> Unit,
viewModel: TaskListViewModel = hiltViewModel(),
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
TaskListScreen(
state = state,
onEvent = viewModel::onEvent,
onOpenTask = onOpenTask,
)
}collectAsStateWithLifecycle() (from androidx.lifecycle:lifecycle-runtime-compose) stops collecting when the lifecycle drops below STARTED. Prefer it to collectAsState() for Android-only code.
The pattern is a route composable (wires ViewModel, navigation and effects) plus a screen composable (pure UI, takes state and lambdas). The screen is trivially previewable and testable.
Navigation
Navigation Compose with type-safe routes
Since Navigation 2.8, routes can be @Serializable types, checked at compile time, replacing string routes and manual argument parsing. This requires the Kotlin serialization plugin.
@Serializable data object TaskList
@Serializable data class TaskDetail(val taskId: Long)
@Serializable data object Settings
@Composable
fun AppNavHost(navController: NavHostController = rememberNavController()) {
NavHost(navController, startDestination = TaskList) {
composable<TaskList> {
TaskListRoute(
onOpenTask = { id -> navController.navigate(TaskDetail(id)) },
)
}
composable<TaskDetail> { entry ->
val args = entry.toRoute<TaskDetail>()
TaskDetailRoute(
taskId = args.taskId,
onBack = { navController.popBackStack() },
)
}
composable<Settings> { SettingsRoute() }
}
}A ViewModel scoped to a destination can read arguments via SavedStateHandle.toRoute<TaskDetail>(), so you do not pass arguments by hand.
@HiltViewModel
class TaskDetailViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
repository: TaskRepository,
) : ViewModel() {
private val route = savedStateHandle.toRoute<TaskDetail>()
val task: StateFlow<TaskItem?> = repository.observeTask(route.taskId)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)
}Navigation 3
Navigation 3 reached stable (1.0) in late 2025 and is the successor designed for Compose. Its key idea: you own the back stack as observable state, and a NavDisplay renders it. Routes are keys, and you provide an entry provider that maps each key to content. It is designed for adaptive layouts, where multiple destinations can be shown at once through scenes.
// Verify imports and API names against the current Navigation 3 release notes.
@Serializable data object Home : NavKey
@Serializable data class Detail(val id: Long) : NavKey
@Composable
fun App() {
val backStack = rememberNavBackStack(Home)
NavDisplay(
backStack = backStack,
onBack = { backStack.removeLastOrNull() },
entryProvider = entryProvider {
entry<Home> {
HomeScreen(onOpen = { id -> backStack.add(Detail(id)) })
}
entry<Detail> { key ->
DetailScreen(id = key.id, onBack = { backStack.removeLastOrNull() })
}
},
)
}Treat the Navigation 3 snippet as a shape, not a copy-paste: artifact names, the NavKey serialization requirements and the decorators for ViewModel scoping have been evolving across 1.0 and later releases.
Which should you use?
| Situation | Choice |
|---|---|
| Existing app on Navigation Compose, stable and working | Stay; adopt type-safe routes |
| New app, adaptive layouts (list-detail, multiple panes) | Navigation 3 |
| Kotlin Multiplatform with Compose Multiplatform | Check which navigation library your Compose Multiplatform version supports; Navigation 3 has had multiplatform work, verify the current state |
| Heavy deep-link requirements | Either; test deep links carefully, and verify the current deep-link support of Navigation 3 |
Navigation rules
- Navigation events go to the navigation host, not from deep inside composables. Pass lambdas up to the route level.
- Do not pass large objects as arguments. Pass ids and load data in the destination.
- Scope ViewModels to destinations, or to a nested graph when screens share a flow (a checkout wizard).
- Handle back:
BackHandlerfor custom behaviour, and predictive back animations are expected on current Android. Verify yourandroid:enableOnBackInvokedCallbacksetting and test the gesture.
Dependency injection: Hilt and Koin
| Aspect | Hilt | Koin |
|---|---|---|
| Mechanism | Compile-time code generation (Dagger) | Runtime service locator DSL |
| Failure mode | Build errors for missing bindings | Runtime exceptions (checkable with verification tests) |
| Build cost | Annotation processing (KSP), slower builds | Lighter builds |
| Android integration | First-party, hiltViewModel(), WorkManager | Good Compose integration (koinViewModel()) |
| Kotlin Multiplatform | Android only | Multiplatform |
| Learning curve | Steeper | Gentler |
Both are fine. Choose Hilt for Android-only teams that want compile-time safety and Google's blessing; choose Koin for Kotlin Multiplatform or faster iteration. Manual constructor injection through an AppContainer is also valid for small apps.
@Module
@InstallIn(SingletonComponent::class)
object DataModule {
@Provides @Singleton
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
Room.databaseBuilder(context, AppDatabase::class.java, "app.db").build()
@Provides
fun provideTaskDao(db: AppDatabase): TaskDao = db.taskDao()
@Provides @Singleton
fun provideOkHttp(): OkHttpClient = OkHttpClient.Builder()
.callTimeout(30, TimeUnit.SECONDS)
.build()
}
@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {
@Binds abstract fun bindTaskRepository(impl: DefaultTaskRepository): TaskRepository
}Remember @HiltAndroidApp on the Application class and @AndroidEntryPoint on the Activity. With Navigation 3 or Compose Multiplatform, verify the current hiltViewModel support for your navigation setup.
Room, coroutines, and Flow
Room as the source of truth
Room returns Flow from DAO queries that re-emit when the table changes, which is what makes offline-first Compose apps simple: the UI observes the database; network refreshes write to the database.
@Entity(tableName = "tasks")
data class TaskEntity(
@PrimaryKey val id: Long,
val title: String,
val notes: String,
val done: Boolean,
@ColumnInfo(name = "updated_at") val updatedAt: Long,
)
@Dao
interface TaskDao {
@Query(
"SELECT * FROM tasks WHERE title LIKE '%' || :query || '%' " +
"ORDER BY done ASC, updated_at DESC"
)
fun observe(query: String): Flow<List<TaskEntity>>
@Query("SELECT * FROM tasks WHERE id = :id")
fun observeById(id: Long): Flow<TaskEntity?>
@Upsert
suspend fun upsertAll(tasks: List<TaskEntity>)
@Query("UPDATE tasks SET done = :done, updated_at = :now WHERE id = :id")
suspend fun setDone(id: Long, done: Boolean, now: Long)
}
@Database(entities = [TaskEntity::class], version = 1, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao
}Practical Room advice: export schemas and commit them; write migrations (AutoMigration when possible) and test them with MigrationTestHelper; avoid main-thread queries; keep entities separate from UI models; and verify the current Room release for coroutine driver and Kotlin Multiplatform support if you share the database layer.
Repository
class DefaultTaskRepository @Inject constructor(
private val dao: TaskDao,
private val api: TaskApi,
@IoDispatcher private val io: CoroutineDispatcher,
) : TaskRepository {
override fun observeTasks(query: String): Flow<List<TaskItem>> =
dao.observe(query).map { list -> list.map { it.toItem() } }
override fun observeTask(id: Long): Flow<TaskItem?> =
dao.observeById(id).map { it?.toItem() }
override suspend fun setDone(id: Long, done: Boolean) = withContext(io) {
dao.setDone(id, done, System.currentTimeMillis())
}
override suspend fun refresh(): Result<Unit> = withContext(io) {
runCatching {
val remote = api.fetchTasks()
dao.upsertAll(remote.map { it.toEntity() })
}.onFailure { if (it is CancellationException) throw it }
}
}Note the explicit re-throw of CancellationException: runCatching swallows it, which breaks structured concurrency. Inject dispatchers so tests can replace them.
Coroutine and Flow rules
- Expose
StateFlowfor state, neverMutableStateFlow. Back it with a private mutable property. - Convert cold Flows with
stateIn(WhileSubscribed(5_000)). - Use
flatMapLatestfor search so old queries are cancelled. - Collect in the UI with lifecycle awareness.
viewModelScopefor ViewModel work,rememberCoroutineScopefor UI event work,LaunchedEffectfor composition-bound work.- Never use
GlobalScope. Use an application-scopedCoroutineScopeinjected by Hilt for work that must outlive a screen. - Do not swallow
CancellationException. - Test with
runTestandDispatchers.setMain(see the testing section).
Performance: Baseline Profiles, Macrobenchmark, R8
Why release performance differs
On Android, code starts interpreted or lightly compiled and is JIT-compiled as it runs, with background AOT compilation later. Compose is a large library whose startup and first-scroll paths run through a lot of code. A Baseline Profile tells ART which classes and methods to precompile at install time, which commonly cuts cold start time and first-frame jank substantially. Google's guidance is that Baseline Profiles are among the most effective optimisations available; measure your own improvement rather than trusting generic percentages.
Generating a Baseline Profile
Use the Baseline Profile Gradle plugin (androidx.baselineprofile) with a :baselineprofile module that runs a test on a device or emulator to record critical user journeys.
@RunWith(AndroidJUnit4::class)
class BaselineProfileGenerator {
@get:Rule val rule = BaselineProfileRule()
@Test
fun generate() = rule.collect(
packageName = "com.example.tasks",
includeInStartupProfile = true,
) {
pressHome()
startActivityAndWait()
// Critical journey: scroll the list and open a detail.
device.wait(Until.hasObject(By.res("task_list")), 5_000)
val list = device.findObject(By.res("task_list"))
list.setGestureMargin(device.displayWidth / 5)
repeat(3) { list.fling(Direction.DOWN) }
device.waitForIdle()
list.fling(Direction.UP)
device.findObject(By.res("task_row")).click()
device.waitForIdle()
}
}Expose test tags as resource ids for UiAutomator with Modifier.semantics { testTagsAsResourceId = true } at the root. Generate on a real, rooted or recent-API device or a supported managed device as per the plugin docs, regenerate each release, and check the generated baseline-prof.txt into the app module (the plugin can also generate it in CI). Libraries including Compose ship their own profiles, which your app profile adds to.
Measuring with Macrobenchmark
@RunWith(AndroidJUnit4::class)
class StartupBenchmark {
@get:Rule val rule = MacrobenchmarkRule()
@Test
fun startupCompilationNone() = startup(CompilationMode.None())
@Test
fun startupBaselineProfile() = startup(CompilationMode.Partial())
private fun startup(mode: CompilationMode) = rule.measureRepeated(
packageName = "com.example.tasks",
metrics = listOf(StartupTimingMetric()),
iterations = 10,
startupMode = StartupMode.COLD,
compilationMode = mode,
) {
pressHome()
startActivityAndWait()
}
}
@RunWith(AndroidJUnit4::class)
class ScrollBenchmark {
@get:Rule val rule = MacrobenchmarkRule()
@Test
fun scrollTaskList() = rule.measureRepeated(
packageName = "com.example.tasks",
metrics = listOf(FrameTimingMetric()),
iterations = 8,
compilationMode = CompilationMode.Partial(),
startupMode = StartupMode.WARM,
) {
startActivityAndWait()
val list = device.findObject(By.res("task_list"))
list.setGestureMargin(device.displayWidth / 5)
list.fling(Direction.DOWN)
}
}Rules for honest numbers: benchmark a non-debuggable, minified (R8) release-like build; use a physical mid-range device; run enough iterations; compare CompilationMode.None versus Partial (with profile) versus Full; and track the metrics in CI to catch regressions (StartupTimingMetric, FrameTimingMetric, TraceSectionMetric). Jetpack's JankStats library reports jank in the field.
R8 and release configuration
android {
buildTypes {
release {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
}
}
}R8 does shrinking, optimisation, obfuscation, and resource shrinking. Modern AGP uses R8 full mode by default, so reflection-based libraries (some serialisation, DI and JSON libraries) need keep rules. Libraries from AndroidX, Room, Hilt and Retrofit ship consumer rules; for your own reflection use, add the narrowest -keep rules you can. Always test the release variant; crashes that appear only after minification are a classic ship-blocker. Upload the mapping file to your crash reporter (the Play Console does this automatically for app bundles).
Other performance wins
| Technique | Benefit |
|---|---|
Startup profile and includeInStartupProfile | Faster cold start through DEX layout optimisation |
Avoid heavy work in Application.onCreate | Use App Startup library, lazy init |
| Compose compiler reports plus stability fixes | Fewer recompositions |
| Lazy list keys, content types | Fewer item recompositions |
Modifier.drawWithCache, graphicsLayer | Cheaper drawing |
| Coil with downsampling | Lower memory, faster scroll |
Tracing with trace("name") { } and Perfetto | Pinpoint slow sections |
| Release-mode profiling (not debug) | Correct numbers |
| Android Studio Compose runtime tracing | See recompositions in system traces |
Previews, testing, and screenshot tests
Previews
@Preview(name = "Light", showBackground = true)
@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true)
@Preview(name = "Large font", fontScale = 1.6f, showBackground = true)
@Composable
private fun TaskRowPreview() {
AppTheme {
TaskRow(
task = TaskItem(id = 1, title = "Write the Compose guide", done = false),
onToggle = {},
)
}
}Define multipreview annotations for your standard matrix (themes, font scales, devices), and give every screen composable previews for empty, loading, error and populated states. Because screens take state and lambdas, they preview without Hilt.
ViewModel unit tests
class MainDispatcherRule(
private val dispatcher: TestDispatcher = UnconfinedTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) = Dispatchers.setMain(dispatcher)
override fun finished(description: Description) = Dispatchers.resetMain()
}
class TaskListViewModelTest {
@get:Rule val mainRule = MainDispatcherRule()
private val repository = FakeTaskRepository()
@Test
fun `query filters tasks`() = runTest {
repository.seed(TaskItem(1, "Buy milk", false), TaskItem(2, "Write code", false))
val vm = TaskListViewModel(repository, SavedStateHandle())
val job = launch(UnconfinedTestDispatcher(testScheduler)) { vm.uiState.collect {} }
vm.onEvent(TaskListEvent.QueryChanged("milk"))
advanceTimeBy(300)
assertEquals(listOf("Buy milk"), vm.uiState.value.tasks.map { it.title })
job.cancel()
}
}Use fakes over mocks for repositories; they make tests describe behaviour rather than call sequences. Libraries such as Turbine make Flow assertions concise.
Compose UI tests
class TaskListScreenTest {
@get:Rule val compose = createComposeRule()
@Test
fun toggleCallsEvent() {
var captured: TaskListEvent? = null
compose.setContent {
AppTheme {
TaskListScreen(
state = TaskListUiState(tasks = listOf(TaskItem(1, "Buy milk", false))),
onEvent = { captured = it },
onOpenTask = {},
)
}
}
compose.onNodeWithText("Buy milk").assertIsDisplayed()
compose.onNodeWithContentDescription("Mark Buy milk done").performClick()
assertEquals(TaskListEvent.Toggled(1, true), captured)
}
}Find nodes by semantics (text, content description, role) before test tags; tests that pass by semantics double as accessibility checks. Enable accessibility checks in UI tests where supported (for example enableAccessibilityChecks() on the Compose test rule; verify API availability).
Screenshot tests
| Tool | Runs on | Notes |
|---|---|---|
| Paparazzi (Cash App) | JVM, no emulator | Fast; renders with layoutlib; good for component libraries |
| Roborazzi | JVM with Robolectric | Real Android framework behaviour, compare and record tasks |
| Compose Preview Screenshot Testing (Google) | JVM, from @Preview functions | Tooling is newer; verify its current stability status in the AGP docs |
Screenshot tests catch regressions that logic tests cannot: clipped text at large font scale, dark theme contrast, RTL layout. Record golden images in CI on one environment to avoid renderer drift, and review changes in pull requests as images.
What to test where
| Layer | Tool | Volume |
|---|---|---|
| Domain and ViewModel | JUnit plus fakes plus Turbine | Many |
| Screen composables (state to UI) | Compose test rule, Robolectric or instrumented | Moderate |
| Visual regression | Screenshot tests | One per component state |
| End-to-end journeys | Instrumented tests on managed devices | Few |
| Performance | Macrobenchmark | Per release |
Adaptive layouts, foldables and large screens
Android on tablets, foldables, Chromebooks and desktop windowing is a first-class target. Recent Android platform versions are removing the ability for apps to opt out of resizing and orientation restrictions on large screens for apps targeting new API levels; check the current behaviour-change documentation for your target SDK. Plan for arbitrary window sizes rather than device types.
Window size classes
@Composable
fun AdaptiveTaskScreen(...) {
val windowSizeClass = currentWindowAdaptiveInfo().windowSizeClass
val isExpanded = windowSizeClass.isWidthAtLeastBreakpoint(WindowSizeClass.WIDTH_DP_MEDIUM_LOWER_BOUND)
// choose layout...
}The window size class breakpoints are compact (under 600dp), medium (600 to 840dp) and expanded (840dp and above), with additional larger classes in recent versions. Use currentWindowAdaptiveInfo() from the Material 3 adaptive libraries, and verify the exact helper names in your adaptive library version since they have evolved.
Canonical layouts
NavigationSuiteScaffoldswitches between bottom bar, rail and drawer based on window size.ListDetailPaneScaffoldshows list and detail side by side when space allows and one at a time otherwise. Pair it with a navigator that handles back correctly.SupportingPaneScaffoldfor main content plus a secondary pane.- Foldables:
WindowInfoTrackerexposes fold features (hinge, tabletop posture) for Jetpack WindowManager. Avoid placing important controls on the hinge.
@OptIn(ExperimentalMaterial3AdaptiveApi::class)
@Composable
fun TaskListDetail(tasks: List<TaskItem>) {
val navigator = rememberListDetailPaneScaffoldNavigator<Long>()
NavigableListDetailPaneScaffold(
navigator = navigator,
listPane = {
AnimatedPane {
TaskList(
tasks = tasks,
onToggle = { _, _ -> },
modifier = Modifier.fillMaxSize(),
)
}
},
detailPane = {
AnimatedPane {
navigator.currentDestination?.contentKey?.let { TaskDetailPane(it) }
}
},
)
}Adaptive rules
- Never branch on device type. Branch on window size.
- Keep state independent of layout. A ViewModel survives a fold or rotation; the layout changes around it.
- Cap content width on large screens (for text,
widthIn(max = 840.dp)), because stretching a phone layout across a 27-inch window is unusable. - Support keyboard, mouse and stylus: focus order, hover states, shortcuts, right-click context menus.
- Test with the resizable emulator and the Android Studio desktop and foldable profiles.
A full worked feature: offline-first task list
This section ties everything together. The structure:
app/src/main/kotlin/com/example/tasks/
├── TasksApplication.kt # @HiltAndroidApp
├── MainActivity.kt # @AndroidEntryPoint, setContent
├── di/DataModule.kt
├── data/
│ ├── local/ (TaskEntity, TaskDao, AppDatabase)
│ ├── remote/ (TaskApi, TaskDto)
│ └── DefaultTaskRepository.kt
├── domain/ (TaskItem, TaskRepository)
├── ui/
│ ├── tasklist/ (TaskListViewModel, TaskListRoute, TaskListScreen, TaskRow)
│ ├── taskdetail/
│ └── theme/
└── navigation/AppNavHost.ktGradle dependencies (version catalog excerpt)
[versions]
# Verify every version below against the current release notes before use.
kotlin = "2.x"
agp = "9.x"
composeBom = "2026.xx.xx"
hilt = "2.5x"
room = "2.x"
lifecycle = "2.x"
navigation = "2.x"
coil = "3.x"
[libraries]
androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" }
androidx-compose-material3 = { module = "androidx.compose.material3:material3" }
androidx-compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navigation" }
androidx-room-runtime = { module = "androidx.room:room-runtime", version.ref = "room" }
androidx-room-ktx = { module = "androidx.room:room-ktx", version.ref = "room" }
androidx-room-compiler = { module = "androidx.room:room-compiler", version.ref = "room" }
hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hilt" }
hilt-compiler = { module = "com.google.dagger:hilt-android-compiler", version.ref = "hilt" }
androidx-hilt-navigation-compose = { module = "androidx.hilt:hilt-navigation-compose", version = "1.x" }
coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" }The version values are intentionally placeholders; copy real versions from the official release pages for each library.
The screen composable
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskListScreen(
state: TaskListUiState,
onEvent: (TaskListEvent) -> Unit,
onOpenTask: (Long) -> Unit,
modifier: Modifier = Modifier,
) {
val snackbarHost = remember { SnackbarHostState() }
LaunchedEffect(state.errorMessage) {
state.errorMessage?.let {
snackbarHost.showSnackbar(it)
onEvent(TaskListEvent.ErrorShown)
}
}
Scaffold(
modifier = modifier,
topBar = { TopAppBar(title = { Text("Tasks") }) },
snackbarHost = { SnackbarHost(snackbarHost) },
) { padding ->
PullToRefreshBox(
isRefreshing = state.isRefreshing,
onRefresh = { onEvent(TaskListEvent.Refresh) },
modifier = Modifier.padding(padding),
) {
Column {
SearchField(
query = state.query,
onQueryChange = { onEvent(TaskListEvent.QueryChanged(it)) },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 8.dp),
)
if (state.tasks.isEmpty() && !state.isRefreshing) {
EmptyState(query = state.query)
} else {
TaskList(
tasks = state.tasks,
onToggle = { id, done -> onEvent(TaskListEvent.Toggled(id, done)) },
onOpen = onOpenTask,
modifier = Modifier
.fillMaxSize()
.semantics { testTagsAsResourceId = true }
.testTag("task_list"),
)
}
}
}
}
}
@Composable
private fun EmptyState(query: String) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
text = if (query.isBlank()) "Nothing to do. Pull to refresh." else "No tasks match \"$query\".",
style = MaterialTheme.typography.bodyLarge,
)
}
}
@Composable
fun TaskRow(
task: TaskItem,
onToggle: (Boolean) -> Unit,
onOpen: () -> Unit,
modifier: Modifier = Modifier,
) {
ListItem(
modifier = modifier
.clickable(onClick = onOpen)
.testTag("task_row"),
headlineContent = {
Text(
task.title,
textDecoration = if (task.done) TextDecoration.LineThrough else null,
)
},
leadingContent = {
Checkbox(
checked = task.done,
onCheckedChange = onToggle,
modifier = Modifier.semantics {
contentDescription = "Mark ${task.title} done"
},
)
},
)
}PullToRefreshBox is a Material 3 component in current releases; verify its availability and whether it is still marked experimental in your Material 3 version. Notice how the error is shown through a snackbar and then acknowledged, which clears the state.
Wiring
@HiltAndroidApp
class TasksApplication : Application()
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
AppTheme {
AppNavHost()
}
}
}
}enableEdgeToEdge() is effectively required in current Android versions for apps targeting recent SDKs, and Scaffold handles insets for you when you use its padding parameter correctly. Check each screen on gesture navigation and three-button navigation.
Lab: verify the feature end to end
- Run unit tests for the ViewModel and repository (
./gradlew testDebugUnitTest). - Run Compose UI tests on an emulator (
./gradlew connectedDebugAndroidTest). - Record screenshot tests for empty, populated and error states in light, dark, and large font.
- Check recomposition: open the Layout Inspector with recomposition counts and toggle a task. Only the changed row should recompose.
- Generate a Baseline Profile from the journey described in the Baseline Profile section.
- Run Macrobenchmark with
CompilationMode.NoneandPartial, and record startup and scroll numbers on a mid-range device. - Build release with R8 and run the app manually and via the UI test suite against the release variant.
- Resize the window in the resizable emulator and swap in
ListDetailPaneScaffoldfor large widths. - TalkBack walkthrough: every control has a meaningful label, and the checkbox announces its state.
Accessibility and semantics
- Use
Modifier.semanticsandcontentDescriptionfor non-text elements; give decorative imagescontentDescription = null. - Use
Modifier.toggleable,selectableandclickable(role = ...)so TalkBack announces roles and states. - Respect font scale and test at 200 percent; avoid fixed heights on text containers.
- Touch targets of at least 48dp; Material components handle this, custom clickable boxes do not.
- Merge semantics for rows (
Modifier.semantics(mergeDescendants = true)) so TalkBack reads one item. - Colour contrast: test both light and dark themes; dynamic colour can produce low contrast combinations with custom surfaces.
- Support reduced motion where you animate large movements, and keyboard focus traversal for tablet and desktop users.
Where this usually goes wrong
- Putting state in the wrong place: ViewModel state in
remember, UI-only state in the ViewModel, or ViewModels passed down into leaf composables. - Passing ViewModels deep into the tree instead of state and lambdas. It breaks previews and tests.
- Missing
keyinLazyColumn, causing wrong state and animation glitches. - Allocating in composition: creating lists, formatters or brushes on each recomposition without
remember. - Using
collectAsStatefor Android-only flows instead ofcollectAsStateWithLifecycle. - Launching coroutines in the composable body, or in
onClickviaGlobalScope. - Using
derivedStateOfeverywhere, or not using it where a fast-changing input drives a slow-changing output. - Assuming strong skipping fixes everything. New instances of unstable objects on each recomposition still defeat skipping.
- Benchmarking debug builds. They aren't representative; always benchmark minified, release-like builds.
- Having no Baseline Profile, which leaves the easiest startup win unclaimed.
- Treating one-off events as a
SharedFlowand losing them on configuration change. Prefer state with acknowledgement. - Passing big arguments in navigation. Pass ids.
- Not testing release builds with R8; reflection issues appear only there.
- Hard-coding phone layouts, then discovering the app is unusable on a tablet or a resized window.
- Ignoring accessibility semantics until the end.
When not to do this
- Don't rewrite a working View-based app to Compose wholesale. Use interoperability (
ComposeViewin XML,AndroidViewin Compose) and migrate screen by screen when you touch them. - Don't add a domain layer and use cases for a CRUD screen where they would be pass-through wrappers.
- Don't split into dozens of Gradle modules prematurely. Modularise when build times or ownership boundaries demand it.
- Don't adopt Navigation 3 on a mid-flight project just to be modern unless adaptive navigation needs justify it.
- Don't annotate everything
@Immutableto quiet reports. - Don't use Hilt in a Kotlin Multiplatform common module; use Koin or manual injection there.
- Don't chase micro-optimisations before measuring; profiles and traces first.
- Don't trust version numbers or API names in any article, including this one; confirm against current release notes.
Pre-release checklist
STATE AND ARCHITECTURE
[ ] One immutable UiState per screen; state flows down, events flow up
[ ] Screen composables are stateless and previewable; route composables wire ViewModels
[ ] collectAsStateWithLifecycle everywhere
[ ] No GlobalScope; CancellationException not swallowed
[ ] SavedStateHandle used for state that must survive process death
PERFORMANCE
[ ] Lazy lists have key and contentType
[ ] Compose compiler reports reviewed; no unexpected unstable hot-path params
[ ] Baseline Profile generated and checked in; regenerated this release
[ ] Macrobenchmark startup and scroll numbers recorded on a mid-range device
[ ] R8 enabled; release build manually smoke-tested; mapping file uploaded
NAVIGATION
[ ] Type-safe routes or Navigation 3 keys; ids not objects as arguments
[ ] Deep links and predictive back tested
[ ] Back stack restoration after process death verified
QUALITY
[ ] ViewModel unit tests with fakes
[ ] Compose UI tests by semantics
[ ] Screenshot tests for light, dark, large font, RTL
[ ] Room schema exported; migrations tested
ADAPTIVE AND ACCESSIBLE
[ ] Tested at compact, medium, expanded widths and in a resized window
[ ] Foldable posture checked on an emulator
[ ] TalkBack pass; font scale 200 percent; 48dp touch targets
[ ] Edge-to-edge insets correct in both navigation modesQuestions that come up
Is Compose faster than Views? For most screens it is comparable once you apply Baseline Profiles and avoid unnecessary recomposition. Its advantages are developer productivity and consistency, not a guaranteed speed edge. Measure your own screens.
Do I still need @Stable and @Immutable?
Less than before thanks to strong skipping, but they still matter for types you want to compare by equals and for library models. Use compiler reports to decide.
Where should a ViewModel be created?
At the route level of each destination via hiltViewModel() or viewModel(), scoped to the navigation entry. Do not create them in deep child composables.
How do I handle one-off events such as navigation or snackbars? Model them as state the UI consumes and acknowledges. If you use a channel, collect lifecycle-aware and understand that delivery is best-effort.
How do I debug excessive recomposition? Use Layout Inspector recomposition counts, Compose compiler reports, and system traces. Fix by deferring state reads, passing stable inputs and splitting composables.
Can I share Compose code with iOS? Yes, with Compose Multiplatform, which has had stable iOS support since 1.8.0; check which AndroidX libraries (Room, ViewModel, Navigation) have multiplatform artifacts at your version.
Sources and docs
- Jetpack Compose documentation
- Compose state and hoisting
- Compose performance and stability
- Strong skipping mode
- Android architecture guide
- Navigation Compose type safety
- Jetpack Navigation 3 is stable
- Room documentation
- Baseline Profiles overview
- Macrobenchmark
- Shrink, obfuscate and optimise your app (R8)
- Adaptive layouts in Compose
- Testing Compose
- Paparazzi
- Roborazzi
- Compose BOM mapping