Data layer: Room & networking

Room with Flow, Retrofit/Ktor, caching, and single-source-of-truth repositories. The offline-cache-then-network pattern shows up in most take-homes.

About 22 min read3-question knowledge check

The mental model

A good librarian is your single point of contact for any book. You do not care whether the book is on the shelf upstairs, in the basement archive, or has to be ordered from another branch — you ask the librarian, and they figure out the fastest way to get it to you, keeping a copy on the local shelf so the next request is instant. The repository is that librarian, and the local database is the shelf. The screen asks the repository for data; the repository decides whether to serve the cached copy, fetch from the network, or both — and the screen never talks to the network or the database directly.

The load-bearing pattern is single source of truth (SSOT): the local database is what the UI reads from, always. The network is not a source the UI reads; it is a writer that updates the database. This inversion is the whole game. In the naive design, the screen reads from the network and falls back to a cache — so a flaky connection blocks the screen, and the cache is a second-class citizen. In the SSOT design, the screen reads from the database (which is always fast and always available), and the network's only job is to keep that database fresh in the background. The app works offline by default because "read the database" never needs a network.

The pattern that shows up in nearly every Android take-home and interview is **cache-then-network** (also called "offline-cache-then-refresh"): the UI observes the database via a reactive stream (a Room Flow), so it shows cached data instantly; meanwhile the repository fetches from the network and writes the result into the database, which *automatically* pushes the update to the UI through the same Flow. One code path, two data events, zero manual "now refresh the screen" logic.

The idea interviewers grade: **the repository owns the decision of where data comes from, the database is the single source of truth, and reactivity connects writes to the UI for free.** A candidate who has the screen do if (online) fetch() else readCache() has missed the pattern; a candidate who exposes a Flow from Room and treats the network as a background writer has it.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision