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.

What was checked, and how: read this first
Checked in the docs (two searches, summaries only): a local database is the recommended source of truth for offline-first, and the repository fetches from the network and persists to the local source; Retrofit and Room suspend functions are main-safe (from a codelab the docs now mark deprecated); cleartext HTTP is off by default from Android 9 and is allowed per domain through a network security configuration, with the manifest flag being phased out. Checked only in repositories and blog posts: the converter is attached with 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

<!-- AndroidManifest.xml, outside the <application> element --> <uses-permission android:name="android.permission.INTERNET" />
// Module build.gradle.kts (versions are placeholders; the converter coordinates are to be confirmed) dependencies { implementation("com.squareup.retrofit2:retrofit:<retrofit-version>") implementation("com.squareup.retrofit2:converter-kotlinx-serialization:<retrofit-version>") }
  • (general knowledge) Without the INTERNET permission 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

import retrofit2.http.GET interface NotesApi { // suspend: Retrofit runs it off the main thread for you @GET("posts") suspend fun getNotes(): List<RemoteNoteDto> }
import okhttp3.MediaType.Companion.toMediaType import retrofit2.Retrofit import retrofit2.converter.kotlinx.serialization.asConverterFactory object NetworkModule { val notesApi: NotesApi by lazy { Retrofit.Builder() .baseUrl("https://jsonplaceholder.typicode.com/") // https, so no cleartext issue .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .build() .create(NotesApi::class.java) } }
  • @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 json from Chapter 6, so ignoreUnknownKeys applies. (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 withContext is 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.

@Entity( tableName = "notes", indices = [Index(value = ["remoteId"], unique = true)] ) data class NoteEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val text: String, val createdAt: Long = System.currentTimeMillis(), val remoteId: Long? = null // the server's id, or null for a note made here ) // In AppDatabase: raise the version (schema changed) @Database(entities = [NoteEntity::class], version = 2, exportSchema = false)
@Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(notes: List<NoteEntity>)
// DTO to entity: the server's id goes in remoteId, our own id is generated fun RemoteNoteDto.toEntity() = NoteEntity(text = title, remoteId = id)

(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

sealed interface RefreshResult { data object Success : RefreshResult data object NoConnection : RefreshResult data class ServerError(val code: Int) : RefreshResult data object BadReply : RefreshResult } // In NotesRepository suspend fun refresh(): RefreshResult
import java.io.IOException import kotlinx.serialization.SerializationException import retrofit2.HttpException class DefaultNotesRepository( private val noteDao: NoteDao, private val api: NotesApi ) : NotesRepository { // getNotesStream, addNote and deleteNote are unchanged: the UI still reads only from Room override suspend fun refresh(): RefreshResult = try { val remote = api.getNotes() noteDao.insertAll(remote.map { it.toEntity() }) // write into the single source of truth RefreshResult.Success } catch (e: IOException) { RefreshResult.NoConnection } catch (e: HttpException) { RefreshResult.ServerError(e.code()) } catch (e: SerializationException) { RefreshResult.BadReply } }

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.

val notesRepository: NotesRepository by lazy { DefaultNotesRepository(database.noteDao(), NetworkModule.notesApi) }
// In FakeNotesRepository override suspend fun refresh(): RefreshResult = RefreshResult.Success

Loading and Error States in the ViewModel and Screen

data class NotesUiState( val notes: List<Note> = emptyList(), val isLoading: Boolean = false, val isRefreshing: Boolean = false, // new val userMessage: String? = null )
private val isRefreshing = MutableStateFlow(false) val uiState: StateFlow<NotesUiState> = combine(repository.getNotesStream(), message, isRefreshing) { notes, userMessage, refreshing -> NotesUiState( notes = notes, isLoading = false, isRefreshing = refreshing, userMessage = userMessage ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = NotesUiState(isLoading = true) ) fun refresh() { viewModelScope.launch { isRefreshing.value = true val result = repository.refresh() isRefreshing.value = false when (result) { RefreshResult.Success -> Unit RefreshResult.NoConnection -> message.value = "No connection" is RefreshResult.ServerError -> message.value = "Server error (${result.code})" RefreshResult.BadReply -> message.value = "Unexpected reply from the server" } } }
// In NotesScreen: a refresh button and a spinner Row { Button(onClick = onRefresh, enabled = !state.isRefreshing) { Text("Refresh") } if (state.isRefreshing) CircularProgressIndicator() }

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 happenedRepository returnsUser sees
Fetch workedSuccessThe list updates by itself, because Room's Flow emits
No networkNoConnection"No connection"; the saved notes still show
Server replied with an errorServerError(code)"Server error (404)"
Reply could not be readBadReply"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.

Compared with the Classic UI course
Android Development: Architecture & Data 4 teaches REST calls, Gson or Moshi, error handling and loading states, with 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

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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.

๐Ÿ“„ View solution
Exercise 3

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 solution
Not Yet Verified
Checked in the docs (summaries only): local database as the recommended source of truth; the repository fetching and persisting; Retrofit and Room suspend functions being main-safe (a deprecated codelab); cleartext off by default from Android 9; per-domain allowance through a network security configuration; usesCleartextTraffic 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).
Coming up
Chapter 8 adds DataStore: a small, safe place for settings such as a sort order or a dark-mode choice, replacing SharedPreferences.