Two-week programme · Day 9 of 14
Eleven green ticks and one amber badge
Part 1Basics
Everything so far happened below the screen. Good news: the screen barely needs to know about any of it.
A screen simply watches the database. When a row changes, for any reason, the screen redraws. It never asks whether the network is up or whether sync ran. That one rule removes most of the complexity people expect here.
Words you need today
- ViewModel
- The class that prepares data for a screen, and survives the screen being rotated.
- Observable query
- A database query that emits a new result each time its data changes.
- Reducer
- A plain function that turns data into the state a screen should show.
- UI state
- Everything a screen can show, named: loading, content, empty, error.
- List diff
- Comparing old and new lists, so only changed rows get redrawn.
- React Native
- A way to write app screens in JavaScript, with native code underneath.
The story
When Priya opens job j-84, the ViewModel subscribes to a database query. The first frame draws from SQLite in about 50 ms, with no network involved. She taps leaking, the query emits, and the row shows a clock. Sync finishes, the query emits, and the clock becomes a tick. A conflict arrives, the query emits, and the row turns amber.
No screen code ever asks about the network. Every change arrives through one door. When 140 pulled changes land in one transaction, the query emits once, and a list diff redraws only the rows that changed.
Now suppose the same company ships a React Native app. When WorkManager wakes it at 4:12 pm, the JavaScript runtime may not be running at all, and React Native screens certainly aren't. So sync must live in native code, and JavaScript just observes the database.
Part 2Today's question
How does a screen stay simple while all of this happens underneath it?
By the end of this lesson, you should be able to:
- List every UI state for a synced row
- Explain one-way data flow
- Split native and JS work in React Native
Part 3In detail
Step by step
- The screen subscribes. On opening, the ViewModel subscribes to a query. The first result draws in about 50 ms, with no network.
- The user edits. The edit goes to the database, not to the screen. The query emits, and the row shows a clock.
- Sync finishes. Sync writes to the same database. The query emits, and the clock becomes a tick.
- A conflict arrives. Same path again. The row's state is now conflict, so it turns amber.
- Many changes arrive. 140 changes commit in one transaction, the query emits once, and a list diff redraws only what changed.
Name every state before you build
Each row is synced, pending, conflict or failed. Each screen is loading, content, empty or error. Design and test every combination, because users always find the one you skipped.
Data flows one way
The database emits, a reducer produces a new immutable state, and the UI renders it. User intents go back through a repository. This makes screens testable without a network, and it makes bugs traceable.
The code, explained
This is the real code, and our tests run it. Read each block, then the notes under it.
Every state a row can show
Name the states before you build the screen. The compiler then makes sure no screen forgets one.
1/** Everything one row can show. The compiler makes every screen handle all of them. */2sealed interface RowUi {3 data object Synced : RowUi4 data object Pending : RowUi5 data class Conflict(val mine: String, val theirs: Theirs) : RowUi6 data class Failed(val reason: String) : RowUi7}8 9/** A pure function: the same row always draws the same way, so it needs no network to test. */10fun rowUi(job: Job): RowUi = when (job.syncState) {11 SyncState.SYNCED -> RowUi.Synced12 SyncState.PENDING -> RowUi.Pending13 SyncState.CONFLICT -> {14 val theirs = checkNotNull(job.theirs)15 RowUi.Conflict(job.answers[theirs.field].orEmpty(), theirs)16 }17 SyncState.FAILED -> RowUi.Failed(job.error ?: "Could not save")18}sealed interface RowUi- A closed list. Adding a state breaks the build wherever it isn't handled.
fun rowUi(job: Job)- A pure function, with no network or clock involved, so a test needs only a row.
RowUi.Conflict(job.answers...- Carries both values, so the resolver screen has what it needs.
Compiled and tested by npm run test:mobile.
A screen as one mapping
The whole list is a transformation of one database query. That's why the screen needs no sync logic.
1data class JobRow(val id: String, val ui: RowUi)2data class ListSummary(val rows: List<JobRow>, val ticks: Int, val needsReview: Int)3 4/** The whole screen is one mapping over the database query. It never mentions the network. */5fun jobList(db: LocalDb): Flow<ListSummary> = db.jobs6 .map { jobs ->7 val rows = jobs.values.sortedBy { it.id }.map { JobRow(it.id, rowUi(it)) }8 ListSummary(rows, rows.count { it.ui is RowUi.Synced }, rows.count { it.ui is RowUi.Conflict })9 }10 .distinctUntilChanged()db.jobs.map { ... }- Each commit produces one new screen state, whoever made the change.
distinctUntilChanged()- If a sync changed nothing visible, nothing redraws.
val ticks: Int- The eleven green ticks and one amber badge are simply counts of this list.
Compiled and tested by npm run test:mobile.
Redrawing only what changed
140 pulled changes may touch three rows on screen. Compose and RecyclerView do this for you, and this is the idea underneath.
1/** Which rows must redraw. 140 pulled changes may touch only a few rows on screen. */2fun changedRows(old: List<JobRow>, new: List<JobRow>): Set<String> {3 val before = old.associateBy { it.id }4 return new.filter { before[it.id] != it }.map { it.id }.toSet()5}old.associateBy { it.id }- Looks up each row's previous state in constant time.
before[it.id] != it- Data classes compare by value, so an unchanged row doesn't redraw.
Compiled and tested by npm run test:mobile.
What can go wrong
- Each screen calls the network itself
- You get duplicate logic, and bugs that appear only offline. Keep all network code inside sync.
- A state was never designed
- Users hit it anyway. List each state before building, and screenshot-test it.
- In React Native, the OS wakes the app with no JavaScript running
- Put sync in native code, and let JavaScript only watch the database.
Decisions to defend
- Where does sync live in a React Native app? Native module, sharing the database, not javaScript background task. The OS can wake you without a running JS runtime, and the work must still happen.
Part 4Questions and answers
Answer out loud first, then open each one.
Why not update the screen directly after a tap and write to the database later?
What is the optimistic update here?
Part 5Going further
The three questions, for today
- Where does it live?
- In the database. The screen holds only state derived from it.
- Who runs the next step?
- The database query emits, and the screen redraws.
- What if it runs twice?
- The reducer is pure, so the same data always draws the same screen.
Practise
- Build25 minSearch-as-you-type with debounce and cancellation
Cancelling stale work is the same one-way flow with a user typing.
Optional reference pages
You don’t need these for the lesson. They hold more detail if you want it later.
Same parts, new product. Tomorrow an edit becomes a chat message, and order suddenly matters.