Offline-First Architecture Flashcards
DATA › Offline
- What is the single source of truth in an offline-first app, and why?
- The local data source (e.g. Room). All higher layers read only from it, so the UI stays consistent regardless of connectivity, and network responses are written to local before being observed.
- Describe the stale-while-revalidate (NetworkBoundResource) pattern.
- Emit cached local data immediately so the UI renders instantly, then fetch fresh network data in the background, write it to the local store, and let observers (Flow) re-emit the updated value.
- Compare online-only, queued, and lazy (local-first) write strategies.
- Online-only writes to network first and must succeed (e.g. payments). Queued writes enqueue and drain when online, tolerating eventual failure (e.g. analytics). Lazy writes update local immediately then queue the network sync; best for critical user data you can't lose.
- Why use WorkManager for offline sync instead of a coroutine in a ViewModel?
- WorkManager persists work across process death and reboots, supports constraints like NetworkType.CONNECTED, and gives automatic exponential-backoff retries via Result.retry(), so sync survives the app being killed.
- How does last-write-wins conflict resolution work and what does it need?
- Each write carries a timestamp; on sync the server (the authority) keeps the newest write and discards older ones. It's simple but can silently drop concurrent edits, so it needs reliable timestamps/versioning.
- Why expose reads as Flow/StateFlow rather than one-shot suspend calls?
- Observable streams make the UI reactive: any local write automatically re-emits, so the screen updates without manual refresh. This is what lets a write-then-observe loop keep UI in sync with the single source of truth.
- Pull-based vs push-based synchronization: when do you choose each?
- Pull (fetch on demand, e.g. Paging RemoteMediator) suits brief offline periods and avoids over-fetching. Push (sync a baseline up front, react to server change signals) suits long offline periods and relational data but needs versioning and server support.
- How should you handle errors when reading from the local source in a Flow?
- Use the catch operator on the Flow to emit an error UI state instead of crashing, typically modeling state with an LCE (Loading/Content/Error) sealed interface exposed via StateFlow.
- What role does Jetpack Paging's RemoteMediator play in offline-first?
- RemoteMediator is the pull-based bridge: it fetches network pages, writes them into the local Room DB, and Paging serves the UI from that local cache, so previously loaded pages remain available offline.