skip to content

In a layered mobile app, which layer should move store, network and heavy work off the UI thread, and why not the screen?

level: middleimportance: should knowfreq 40%

answer

  1. the UI thread draws and takes input
  2. whoever blocks, moves the work
  3. safe to call from the UI thread
  4. results return as state
  5. work outliving the screen needs a longer scope

basics

~20 s

The layer that does the blocking work, data sources, repositories and any heavy use case, moves it off the UI thread itself, so every call is safe from the UI thread and screens never manage threads.

solid answer

~50 s

The UI thread draws frames and handles touches; a store query, a network call or totalling a year of sets for a chart blocks it, and the app stutters or freezes. The rule is that each class is responsible for its own concurrency: a data source reading the store or the server moves that work to a background thread itself, a repository filtering a big list does the same, so calling any of them from the UI thread is safe. The screen and its state holder just call and observe; results come back as new state, applied on the UI thread. A second boundary is lifetime: a fetch whose result should be stored even if the user leaves the screen runs in a scope owned by the repository rather than the screen, and work that must survive the app being killed is handed to an OS-managed background mechanism.

go deeper

for a junior

Recall that slow work must not run on the UI thread, which draws the screen and handles touches, and name the slow things: store, network, heavy computation.

for a middle

Explain the rule that the class doing the blocking work moves it, so every call is safe from the UI thread, and how results return to the screen as state.

for a senior

Show the lifetime boundary: screen-scoped, repository-scoped and must-finish work, and the bug where leaving a screen cancels a refresh that should have been stored. Cover shared mutable data.

for a principal

Turn threading and scopes into a team rule enforced in review, so no screen manages threads and every long operation states which lifetime it belongs to.

## Why the UI thread is precious Mobile UI toolkits, native and cross-platform alike, have a **UI thread**: the thread that runs layout, drawing and input handling. The toolkits are generally not built for concurrent access, so screen updates are applied on that thread. Anything slow that runs there delays the next frame and the next touch: - reading or writing the local store; - a network call, which can take seconds on a weak signal; - decoding a large response; - heavy computation, such as weekly totals over a year of logged sets for a progress chart. The visible results are dropped frames while scrolling, a button that does not respond, and a screen that seems frozen during a slow call. ## The rule: whoever blocks, moves the work The cleanest rule assigns threading to the class that does the blocking work. A class is **safe to call from the UI thread** when it moves its own long-running work to a background thread before doing it. That gives every layer a clear duty: | Layer | Threading responsibility | In the workout app | |---|---|---| | Data sources | Run store and network I/O off the UI thread | The set table's queries, the plan API call | | Repositories | Move their own heavy work, such as filtering or merging big lists | Merging a server history snapshot into stored rows | | Use cases | Move their own long work, after checking it does not belong in the data layer | Personal-record detection over many sets | | State holder | None for I/O; builds state from results | Turns sets into chart state | | Screen | None; renders on the UI thread | Draws the chart | Why not let the screen decide? Because the screen does not know what a call costs. A repository that reads memory today may read the store tomorrow; if every caller wraps calls in its own background work, a change in the data layer silently becomes a freeze on whichever screen forgot. Putting the responsibility where the knowledge is removes the class of bug. ## Results come back as state The background work finishes on some other thread, but the screen must be updated on the UI thread. In a layered design this handoff happens at one place: the state holder receives results from the repository's observable data and publishes a new screen state, which the screen renders on its own thread. Screens never receive raw callbacks from background threads. ## Lifetime is a boundary too Threading answers "which thread"; the layers also answer "how long". Operations fall into three groups: 1. **Screen-scoped.** Loading the data a screen displays. If the user leaves, the work can be cancelled with the screen. 2. **App-scoped.** Work whose result is worth keeping even if the user leaves the screen, such as refreshing today's plan into the store. It runs in a scope owned by the repository, so it finishes and writes the store; it still ends if the process is killed. 3. **Must finish.** Work that must complete even if the OS kills the app, such as delivering a finished workout to the server. It is handed to an OS-managed background mechanism, such as a deferrable-work scheduler or a system-run background transfer; what each platform guarantees, and how that work is budgeted, is the background-work design's subject. Putting a plan refresh in the screen's scope is a common bug: the user taps back during a slow refresh, the request is cancelled, and the store never gets the new plan. ## Shared data across threads Moving work off the UI thread creates concurrency inside the data layer: - A repository's in-memory copy updated by two background tasks needs protection, such as a lock or confining all writes to one serial background queue. - Exposing immutable values means readers on any thread can never see a half-updated object. - Related store writes go in one transaction, so observers never read a partial change. ## Mistakes - Wrapping every repository call in background work at each screen, duplicated and easy to forget. - Assuming local store access is fast enough for the UI thread. - Applying results to the screen from the thread that produced them. - Starting a refresh that should be stored in the screen's scope, so leaving the screen cancels it. - Assuming background threads make a repository's shared cache safe.

  • If the user leaves the plan screen while its refresh is in flight, should the request be cancelled?
    It depends on the operation. If the result is worth storing, as a refreshed plan is, run it in a scope owned by the repository so it completes and writes the store. If it only feeds that screen, such as a search typed into it, cancel it with the screen to save battery and data.
  • A repository keeps an in-memory copy of today's plan that two background tasks update. What must it do?
    Protect it: guard reads and writes with a lock, or confine all writes to one serial background queue, and expose immutable snapshots. Otherwise one task can overwrite the other's change or a reader can see a half-updated value.

  • Each screen should wrap repository calls in its own background work.
  • Local store reads are fast enough to run on the UI thread.
  • Results can update the screen from whichever thread produced them.
  • Any work started from a screen should outlive that screen to be safe.
  • Running on background threads makes a shared in-memory cache safe.