Theory

The network, Retrofit and suspend

Until now the menu was "from code". But real Pica keeps its pizzas on the server — the Go backend you ran in lesson 1. Time to connect.

To talk to the server we use Retrofit — the most popular HTTP library for Android. Its idea is elegant: you describe an interface, and Retrofit writes the network code for you.

interface PicaApi {
    @GET("menu")
    suspend fun getMenu(): List<MenuItemDto>
}

A few concepts:

  • suspend — a function that can "pause" and resume. A network request is slow, so it runs on a coroutine, not the main thread (otherwise the UI would freeze).
  • DTO (Data Transfer Object) — how the data looks in the JSON from the server. The server sends price_cents (cents), but our UI wants price in euros. So the DTO is separate from the domain MenuItem, with a small translator between them.
  • Repository — a layer between the ViewModel and the API: it gets DTOs, converts them to domain, and returns clean MenuItems.

Important — we wire it BY HAND. In this lesson we build the Retrofit instance (base URL, JSON converter) ourselves, directly. No Koin yet — that arrives in lesson 6. This is deliberate: first feel how much manual wiring it takes, then you'll see what Koin solves.

Let's build: first the service interface + DTO, then the menu from the server onto the screen.