Networking with Retrofit
Android Development with Compose: Architecture & Data
Course 5 ยท Chapter 7 ยท Fetching From a Server
Now the notes can come from the internet. Retrofit turns an interface into HTTP calls; the Chapter 6 Json turns the reply into Kotlin objects; and following Chapter 5, the repository writes what it fetches into Room, so the screen keeps reading from one place and still works offline.
asConverterFactory and a media type, and takes a configured Json. Important: the community converter by Jake Wharton is deprecated, and its repository says the converter moved into Retrofit as a first-party converter. I did not confirm the first-party Gradle coordinates, package or function name, so the code below uses the names I expect and says so; check Retrofit's own documentation first.
General knowledge, not found in any search: the INTERNET permission, the Retrofit annotations, HttpException, the unique-index design and the test service's shape. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.
Setup
- (general knowledge) Without the
INTERNETpermission the app cannot reach the network at all; the search found no current page on it, so this is not docs-checked. - The converter. Search results say the community converter is deprecated and has moved into Retrofit. The coordinates above are my best expectation of the official one. Confirm them in Retrofit's documentation or release notes before use; the old community artifact (last release 2023, per its Maven page) is a fallback to avoid in new code.
The API Interface and the Retrofit Instance
@GET("posts")is appended to the base URL. The service used is a free test API that needs no key and returns pretend data; its address and fields were not checked against its documentation here (Chapter 6 flagged the same). Check it before relying on it.- HTTPS. (docs) Cleartext HTTP is blocked by default from Android 9, so an
http://address would fail. The docs say to allow cleartext only for specific domains through a network security configuration, not app-wide, and not as a shortcut. - The converter uses the shared
jsonfrom Chapter 6, soignoreUnknownKeysapplies. (blog sources) If you mix converters, add this one last. - Main-safe. (docs, from a deprecated codelab) Retrofit suspend functions are main-safe, so no
withContextis needed here.
Changing the Entity: a Schema Change in Practice
A subtle problem: Room numbers local notes 1, 2, 3, and the server also has notes numbered 1, 2, 3. If you stored the server's ids as ours, the two sets would overwrite each other. So the entity gets a remoteId column, and a unique index on it so a second refresh replaces the same server note instead of duplicating it.
(general knowledge) A unique index allows many rows whose remoteId is null, so notes made on the phone are not affected. Changing the entity means raising the database version, as Chapter 4 said. While developing, the quickest fix is to uninstall the app so the old database is deleted; for a released app you would write a migration instead, so users' notes survive.
The Repository Tells the ViewModel What Happened
Why a result type and not exceptions? Chapter 5's rule: the ViewModel must not know about the data layer's tools. If refresh() let HttpException (a Retrofit class) escape, the ViewModel would have to import Retrofit. Instead the repository turns each failure into a plain value.
(general knowledge) A missing connection normally surfaces as an IOException, a non-success reply as an HttpException from Retrofit's suspend functions, and a reply that does not parse as a SerializationException; confirm what you actually get in Exercise 2.
Only those three are caught, so cancellation (Chapter 3) still passes through.
Loading and Error States in the ViewModel and Screen
The pattern is the same as Chapters 2 and 3: failures become a userMessage that the screen shows once; progress becomes a flag (isRefreshing). (docs) The recommendation to model UI state with a data class holding data, errors and loading signals is from Chapter 1's sources. The route also needs onRefresh = viewModel::refresh.
| What happened | Repository returns | User sees |
|---|---|---|
| Fetch worked | Success | The list updates by itself, because Room's Flow emits |
| No network | NoConnection | "No connection"; the saved notes still show |
| Server replied with an error | ServerError(code) | "Server error (404)" |
| Reply could not be read | BadReply | "Unexpected reply from the server" |
Notice what is missing: after a successful refresh, the ViewModel does not copy the fetched notes into the state. It does not need to. The data went into Room, and the screen reads Room. That is the single source of truth working, and it is why the app still shows its notes on an aeroplane.
LiveData carrying the results. The calls are the same. What changes here: the JSON library is kotlinx.serialization (Chapter 6), results are plain values from the repository, and the network writes into Room rather than going straight to the screen.
Try It Yourself
Add the permission, the dependencies, NotesApi, NetworkModule and the changes to the entity, DAO, repository, ViewModel and screen. Uninstall the app, run it, tap Refresh, then switch on aeroplane mode and restart. Report the converter coordinates you actually used and what you saw offline.
Cause each failure on purpose: no network, a wrong path (for example @GET("postz")), and a URL that returns something that is not the expected JSON. Report the exception type you got each time and whether the repository mapped it as the chapter says.
Make a refresh run automatically the first time the screen opens if the table is empty. Where should that logic live, and why not in the composable? Then explain, in your own words, why the screen reads Room and not the Retrofit reply.
๐ View solutionusesCleartextTraffic being phased out.Repositories and blogs only:
asConverterFactory with a media type and a configured Json; the community converter's deprecation and its move into Retrofit.General knowledge, not found in any search: the INTERNET permission; the first-party converter's Gradle coordinates, package and function name; the Retrofit annotations; which exceptions each failure produces; the unique-index design; the test service's address and fields.
Not verified: every listing and solution (unrun); the exercises (not run by me); the Room 3.0 form of the entity and DAO. Nothing was checked on your install.
Sources: Build an offline-first app (developer.android.com), Data layer (developer.android.com), Network security configuration (developer.android.com), Cleartext communications (developer.android.com), Get data from the internet codelab (developer.android.com), retrofit2-kotlinx-serialization-converter (GitHub, deprecated).