Architecture and UI State

Android Development with Compose: Architecture & Data

Course 5 · Chapter 1 · Organising an App

Android Development Fundamentals with Compose taught you to build screens. This course is about what sits behind them: where data lives, how it reaches the screen, and how the code stays understandable as the app grows. Before any new library, this chapter gives you the picture: layers, the way state and events travel, and the small class that describes what a screen is showing.

What was checked, and how: read this first
Checked in the docs (one web search, summaries only): the recommended layers (UI and data, with an optional domain layer), unidirectional data flow, exposing a single uiState as a StateFlow, modelling it as a data class or a sealed class, repositories between the UI and data sources, and not sending one-off events from a ViewModel to the UI. General knowledge, not checked: the "no architecture" example, the folder layout, and the MVVM wording. All code is unrun (no Kotlin compiler on the machine used to write this). Nothing here was seen on your install. The names NotesUiState, NotesScreen and the ComposeHelloTheme in the previews are examples; use your own project's.

The Problem Architecture Solves

Here is a screen written the easy way, with everything inside the composable:

// Everything in one composable: the "no architecture" version @Composable fun NotesScreen() { var notes by remember { mutableStateOf(listOf<String>()) } var loading by remember { mutableStateOf(true) } LaunchedEffect(Unit) { // network call, database query and parsing all live here notes = loadNotesFromWhereverItLives() loading = false } if (loading) Text("Loading...") else notes.forEach { Text(it) } }

(general knowledge) It works, until it grows. Typical troubles:

  • It cannot be tested without drawing a screen, because the logic is welded to the UI.
  • It cannot be previewed in Android Studio, because the preview would try to call the network.
  • State is lost on rotation (Chapter 2 of Android Development Fundamentals with Compose), and every screen repeats the same loading code.
  • Several screens need the same data, so the same fetching code is copied around.

Layers

(docs) Android's architecture guidance recommends at least two layers, plus an optional third:

LayerJobLives in
UI layerDisplays application data and takes user input. In Compose: your composables, plus the state holder (a ViewModel) that prepares what they show.ui/
Data layerHolds the business logic and exposes app data. Repositories sit here and hide where data comes from (database, network, files).data/
Domain layer (optional)Reusable business rules ("use cases"). The docs say it is for reusing logic across ViewModels or simplifying a complex one, and mainly worth it for big apps.domain/

(docs) Two of the recommendations that matter most: repositories sit between the UI and the data sources, so UI components never touch a database or network client directly; and layers talk to each other with coroutines and flows (Chapter 3).

com.example.notes/ ├── ui/ │ ├── notes/ │ │ ├── NotesScreen.kt (composables) │ │ ├── NotesUiState.kt (the state class) │ │ └── NotesViewModel.kt (Chapter 2) │ └── theme/ ├── data/ │ ├── NotesRepository.kt (Chapter 5) │ ├── local/ (Room: Chapter 4) │ └── remote/ (Retrofit: Chapter 7) ├── domain/ (optional: use cases) └── MainActivity.kt

Unidirectional Data Flow

(docs) Unidirectional data flow (UDF) means state flows down from a state holder to the UI, and events flow up from the UI. A tap becomes an event passed upward; the state holder updates the state; the UI redraws from the new state. It is the state hoisting you met in Android Development Fundamentals with Compose 4, applied to the whole screen.

events (taps, typing) ┌──────────────────────────┐ │ ▼ UI (composables) ◄────── state holder (ViewModel) ▲ state flows down │ asks for data │ ▼ │ data layer (repository) │ │ │ ┌─────────┴─────────┐ │ ▼ ▼ │ local database network / files

The benefit: there is one place where the state changes, so a bug in what is shown has one place to look.

UI State: One Class for What the Screen Shows

(docs) The recommendation is to expose a single uiState property from the state holder, modelled as a data class holding the data, errors and a loading flag, or a sealed class when the states are mutually exclusive. Both shapes:

data class NotesUiState( val notes: List<String> = emptyList(), val isLoading: Boolean = false, val errorMessage: String? = null )
sealed interface NotesUiState { data object Loading : NotesUiState data class Success(val notes: List<String>) : NotesUiState data class Error(val message: String) : NotesUiState }

Both are called NotesUiState here, so use one at a time; the screen below uses the sealed interface.

Data class (flags and fields)Sealed interface (one case at a time)
Fits whenSeveral things can be true together (content showing while a refresh runs)The screen is exactly one of loading, content or error
Impossible statesPossible (loading and error at once)Not representable
Reading it in the UIif on the fieldsAn exhaustive when

A Stateless Screen from a UI State

With a state class, the screen becomes a plain function from state to UI, with events as callbacks. That also fixes the preview problem: pass in any state you like.

import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.layout.Column import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview
@Composable fun NotesScreen(state: NotesUiState, onRetry: () -> Unit) { when (state) { NotesUiState.Loading -> Text("Loading...") is NotesUiState.Success -> LazyColumn { items(state.notes) { note -> Text(note) } } is NotesUiState.Error -> Column { Text(state.message) Button(onClick = onRetry) { Text("Try again") } } } } @Preview(showBackground = true) @Composable fun NotesScreenSuccessPreview() { ComposeHelloTheme { NotesScreen(state = NotesUiState.Success(listOf("Buy milk", "Call Ada")), onRetry = { }) } } @Preview(showBackground = true) @Composable fun NotesScreenErrorPreview() { ComposeHelloTheme { NotesScreen(state = NotesUiState.Error("No connection"), onRetry = { }) } }

(docs) The same advice applies to events: the docs say not to send one-off events from the ViewModel to the UI, but to process the event in the ViewModel and show the result through a state update. Chapter 2 builds the ViewModel that supplies this state.

MVVM in One Paragraph

(general knowledge, and the structure the old course called MVVM) Model is the data layer; View is the composables; ViewModel is the state holder in between: it asks the data layer for data and turns it into UI state. The diagram above is MVVM with Compose, with the arrows labelled the way Compose likes them.

Compared with the Classic UI course
Android Development: Architecture & Data 8 teaches the repository pattern, clean architecture basics and the separation of concerns in a View-based setting. The ideas are the same; the difference here is that Compose makes the state-down, events-up rule natural, and StateFlow replaces LiveData as the default way to publish state.

Try It Yourself

Exercise 1

Take the "no architecture" NotesScreen above and list each responsibility it has (drawing, holding state, loading, parsing, and so on). Sort them into UI layer, data layer or "state holder", and say what the screen composable would be left with.

📄 View solution
Exercise 2

Pick a screen of your own (a weather forecast, a recipe list, a to-do list). Write a UI state for it twice: once as a data class and once as a sealed interface. Say which you prefer for that screen and why.

📄 View solution
Exercise 3

Build the stateless NotesScreen and write three @Preview functions, one each for loading, success and error. Check all three in the preview without running the app.

📄 View solution
Not Yet Verified
Checked in the docs (one web search, summaries only): at least two layers with an optional domain layer; repositories between the UI and data sources; coroutines and flows between layers; unidirectional data flow (state down, events up); a single uiState exposed as a StateFlow; data class or sealed class for UI state; no one-off events from the ViewModel to the UI.
General knowledge, not checked: the problems list for the no-architecture version, the folder layout, the MVVM summary, the data class against sealed interface table.
Not verified: every listing and solution (unrun); the imports; the exercises (not run by me). Nothing was checked on your install.
Sources: Guide to app architecture (developer.android.com), Recommendations for Android architecture (developer.android.com), UI layer (developer.android.com), UI State production (developer.android.com), Compose UI Architecture (developer.android.com).
Coming up
Chapter 2 builds the state holder: a ViewModel that exposes a StateFlow of UI state, how a composable collects it, and why the state survives rotation.