Mobile EngineeringVol. 22 · Mobile
0 / 0

Shelves / Mobile Engineering

MB·02

Native UI and App Architecture: Android and iOS

Building native apps the modern way on both platforms: Kotlin with Jetpack Compose and Swift with SwiftUI, declarative UI as a function of state, recomposition and why stable identities and stable inputs matter, unidirectional data flow with ViewModels and observable state, Kotlin coroutines and Flow, Swift concurrency with async/await, actors and the main actor, local persistence (Room, DataStore, SwiftData), navigation, dependency injection and modularisation; with a lab in a small declarative runtime showing how keys and stable callbacks turn 1,000 re-renders into one.

14 topics · ~8 min read · 16-question quiz
Updated Suggest a correction

Start here: UI as a function of state

Both platforms have moved from imperative UI (find a view, change its text) to declarative UI: you write a function that describes what the screen looks like for a given state, and the framework works out what to update when the state changes.

Kotlin
// Jetpack Compose
@Composable
fun OrderCard(order: OrderUi, onOpen: (Long) -> Unit) {
    Card(onClick = { onOpen(order.id) }) {
        Text(order.dish); Text(order.statusLabel)
    }
}
Swift
// SwiftUI
struct OrderCard: View {
    let order: OrderUI
    var body: some View {
        VStack(alignment: .leading) { Text(order.dish); Text(order.statusLabel) }
    }
}

When an order's status changes, the framework re-runs the functions whose inputs changed (Compose calls it recomposition; SwiftUI re-evaluates body) and updates only what's different on screen. Done well, a change touches one card; done badly, it re-renders the whole list on every update.

Measured in a small declarative runtime

The lab built a tiny runtime that, like Compose and SwiftUI, skips a card when its identity and inputs are unchanged, and counted re-renders in a list of 1,000 orders:

How the list is written One order's status changes A new order inserted at the top
identity by position, no skipping 1,000 re-rendered 1,001
stable keys and skipping, but a new lambda passed each time 1,000 1,001
identity by position, skipping, stable callbacks 1 1,001
stable keys, skipping, stable callbacks 1 1

Two details decided everything: identity (a stable key rather than a list position) and stable inputs (equal values and callbacks the framework can recognise as unchanged).

How deep to go

Volume 17 defines six mastery levels. For native UI and architecture:

Level What you can do
L1 Explain declarative UI, state and unidirectional data flow
L2 Build screens with Compose or SwiftUI backed by ViewModels and local storage
L3 Explain recomposition, stability, coroutines/Flow and Swift concurrency
L4 Debug excessive recomposition, leaks, races and threading violations
L5 Design a modular app architecture for a team and its testing strategy
L6 Evolve it across OS versions, team growth and years of releases

Languages

Kotlin (Android, and shared code with Kotlin Multiplatform): null safety in the type system, data classes, sealed types for UI states, extension functions, and coroutines for asynchronous code: suspend functions, structured concurrency (viewModelScope, lifecycleScope cancel work when their owner ends), Flow and StateFlow for streams of values.

Swift (iOS): value types (structs) by default, optionals, enums with associated values, protocols, and Swift concurrency: async/await, structured tasks (async let, task groups), actors that serialise access to their state, the main actor for UI, and Sendable checking; Swift 6's strict concurrency mode turns data races into compile errors.

Declarative UI in depth

  • State: values the UI reads. In Compose, mutableStateOf / StateFlow.collectAsStateWithLifecycle(); in SwiftUI, @State, @Observable models, @Environment.
  • Recomposition / re-evaluation: when state a function read changes, the framework re-runs it. Keep composables small and cheap; read state as low in the tree as possible so changes recompose less.
  • Stability: Compose can skip a composable when all its parameters are stable and equal. Immutable data classes of stable types are stable; List from the standard library isn't guaranteed stable (use immutable collections or the compiler's strong-skipping mode, now the default, plus careful parameters). SwiftUI compares view values; keep view structs small and avoid passing large mutable reference types.
  • Lists: LazyColumn { items(orders, key = { it.id }) { … } } / SwiftUI List(orders, id: \.id): keys give identity (the lab), preserve per-item state and enable animations.
  • Side effects: never in the render function itself; use LaunchedEffect, DisposableEffect (Compose) or .task, .onAppear (SwiftUI) tied to lifecycle.
  • Tools: Compose's layout inspector shows recomposition counts; SwiftUI's Self._printChanges() and Instruments show why views update.

Architecture: unidirectional data flow

Text
UI (Compose / SwiftUI)  ──events (onSkipDay)──→  ViewModel  ──→ use cases / repositories ──→ local DB + network
        ↑                                           │
        └──────── UI state (StateFlow / @Observable) ┘
  • A ViewModel per screen holds UI state as an immutable value (data class CalendarUi(val days: List<DayUi>, val isSyncing: Boolean, val error: String?)), exposes it as a StateFlow / observable property, and handles events.
  • Repositories own data access and hide whether data came from the database or the network; the local database is the source of truth for the UI (chapter 05: offline-first).
  • Use cases (optional) hold business logic shared between ViewModels.
  • UI state is a sealed set of cases (Loading, Content, Error) so every screen handles every case.

Persistence

Need Android iOS
structured data, queries Room (SQLite with compile-time-checked queries, Flow observation) SwiftData or Core Data; GRDB/SQLite
small key–value settings DataStore UserDefaults (non-sensitive only)
secrets (tokens) Keystore-backed encryption Keychain
files app-specific storage app container directories

Migrations matter as much as on servers: users skip versions, so a database at schema version 3 may be upgraded straight to 7. Test every migration path.

Navigation, DI and modules

  • Navigation: Compose Navigation (type-safe routes) or a single-activity graph; SwiftUI NavigationStack with value-based paths; deep links into screens ("open order 88412" from a notification).
  • Dependency injection: Hilt or Koin on Android; initialiser injection and SwiftUI's environment on iOS. The goal is testability: ViewModels receive repositories, tests pass fakes.
  • Modularisation: feature modules (:feature:calendar, :feature:tracking) and core modules (:core:network, :core:database) speed builds, enforce boundaries and let teams work independently.

Testing native code

  • Unit tests for ViewModels and domain logic, with fake repositories and test dispatchers / controllable clocks.
  • UI tests: Compose UI tests (composeTestRule) and XCUITest/SwiftUI previews for critical screens; screenshot tests for visual regressions.
  • Instrumented tests for database migrations and platform integrations.

Common traps

  • Lists without stable keys.
  • New objects and lambdas as parameters in hot lists.
  • Side effects in render functions.
  • Mutable state shared across threads without actors or confinement.
  • Business logic in views.

Lab: identity and stable inputs in a declarative runtime

Setup. A small declarative UI runtime in Python on the lab machine, written to mimic the decision Compose and SwiftUI make: for each item, if an item with the same identity existed last render and all its inputs are equal (the order value and the callback), skip it; otherwise call its render function. It counts render calls. The runtime is an illustration of the mechanism, not the frameworks themselves.

A list of 1,000 orders (immutable records: id, dish, status). Two updates: one order's status changes; a new order is inserted at the top. Four ways of writing the list:

Identity Skip when inputs equal? Callback passed to each card Status change Insert at top
list position no stable 1,000 1,001
stable key (order ID) yes new lambda each render 1,000 1,001
list position yes stable 1 1,001
stable key yes stable 1 1

What it shows

  • Skipping needs equal inputs. One freshly created lambda per item made every card look changed, cancelling the benefit of keys and immutable data. In Compose, lambdas created inside composition are remembered when their captured values are stable; problems appear with unstable captures, mutable classes, or objects created in the parameter list.
  • Identity by position breaks on insertions. Every item shifted position, so every card's inputs "changed". With stable keys, the insertion was one new card. Keys also keep per-item UI state (an expanded section, text being typed) attached to the right order.
  • Cost scales with mistakes: on a phone, 1,000 recompositions on every status update (which arrive every few seconds during delivery tracking) means dropped frames and battery drain; one recomposition is free.

Try it yourself

  1. Make the order record mutable (a class whose equality is identity) and see what happens to skipping.
  2. Add per-item state (expanded or collapsed) and show it moving to the wrong order when identity is positional.
  3. In an Android project, render the same list in LazyColumn with and without key = { it.id } and watch recomposition counts in the layout inspector.
  4. In SwiftUI, use Self._printChanges() in the card view and compare List(orders) with indices versus id: \.id.

Revision sheet: native UI and app architecture

Key ideas

  • Declarative UI: screens are functions of state; frameworks re-run what changed (recomposition / body re-evaluation).
  • Stable identity (keys) and stable, equal inputs let frameworks skip work.
  • Unidirectional data flow: ViewModel owns immutable UI state; UI sends events; repositories hide data sources; local DB as source of truth.
  • Kotlin coroutines and Flow with structured scopes; Swift async/await, actors, main actor, Sendable.
  • Persistence: Room/DataStore/Keystore; SwiftData/Core Data/UserDefaults/Keychain; test migrations.
  • Navigation with deep links; DI for testability; feature and core modules.

Numbers to remember

  • Lab: no keys or unstable callbacks → 1,000 re-renders per change; keys + stable inputs → 1.

Glossary

  • Recomposition: Compose re-running composables whose inputs changed.
  • Stable type: a type whose equality Compose can rely on to skip.
  • StateFlow: a Kotlin observable state holder.
  • Actor: a Swift type serialising access to its state.
  • UDF: unidirectional data flow.