Theory

Why a cache: a single source of truth

So far the menu came only from the network (lesson 5): open the app, see Loading, wait for the response, then the pizzas. No internet — you get Error, a blank screen. But a menu changes rarely. Why wait on the network every time?

We give Pica's menu a cache so it opens instantly and works even offline. The idea is a single source of truth: the screen always shows the local cache, and the network only refreshes it in the background.

Screen  ──observes (Flow)──▶  Room cache  ◀──writes──  refresh() from GET /menu
  • Read: the screen subscribes to the cache's Flow. If there's data, it shows instantly (even offline).
  • Write: refresh() goes to the server, gets a fresh menu and overwrites the cache. The Flow re-emits automatically, and the screen updates itself.

For this we use Room — Google's ORM over SQLite. Three parts:

  • @Entity — a Kotlin class matching a row of a DB table.
  • @Dao — an interface of queries (@Query, @Insert) that can return a Flow.
  • @Database — ties entities and DAOs into one database.

The cache slots naturally into what we already have: MenuRepository from lesson 5 grows (reads the cache, refreshes from the network), and the Room objects are wired through Koin (lesson 6) as a few more singles.

Verify-docs. Room here is the 2.x line (androidx.room 2.8.x), NOT 3.0. The 3.0 line changes KSP/Gradle setup; we stay on 2.x.