Networking, Persistence and Shipping

Article · 2:00

Ktor, Room and the steps between a working app and one on the Play Store.

A real app talks to a server and remembers things. Ktor is the Kotlin-first HTTP client and works on every multiplatform target; Retrofit remains common on Android-only projects. Both pair with kotlinx.serialization, which generates JSON parsing at compile time from a @Serializable data class rather than by reflection at runtime.

For storage, Room wraps SQLite with compile-time-checked queries - a typo in SQL fails the build rather than the app. A DAO function returning a Flow re-emits whenever the underlying table changes, which plugs straight into the ViewModel pattern from the previous topic. For a handful of key-value settings, DataStore replaces SharedPreferences and exposes its values as a Flow too.

The offline-first pattern that follows is worth naming: the database is the single source of truth, the UI only ever observes the database, and the network writes into it. The screen then works offline for free and never shows a spinner where cached data exists.

Shipping requires several concrete steps. Build a release variant with minifyEnabled so R8 shrinks and obfuscates the code. Build an Android App Bundle rather than an APK - Play requires it and it lets Google generate per-device downloads. Sign it with an upload key, and keep that keystore safe, since losing it means you cannot update your own app. Then create the Play Console listing, complete the data safety form honestly, and roll out to a closed track before production.

import kotlinx.serialization.Serializable
import kotlinx.coroutines.flow.Flow

// Parsed at compile time, not by runtime reflection
@Serializable
data class NoteDto(val id: Int, val title: String, val done: Boolean)

// Room: the query is checked when the project builds
// @Dao
// interface NoteDao {
//     @Query("SELECT * FROM notes ORDER BY title")
//     fun observeAll(): Flow<List<NoteEntity>>      // re-emits on any change
//
//     @Upsert
//     suspend fun upsertAll(notes: List<NoteEntity>)
// }

// Offline-first: the database is the single source of truth
class NoteRepository(private val dao: NoteDao, private val api: NoteApi) {

    fun observeNotes(): Flow<List<NoteEntity>> = dao.observeAll()

    suspend fun refresh() {
        val fresh = api.fetchNotes()                 // network writes in
        dao.upsertAll(fresh.map { it.toEntity() })   // UI updates via the Flow
    }
}

// Placeholders so the example reads as one piece
interface NoteApi { suspend fun fetchNotes(): List<NoteDto> }
interface NoteDao {
    fun observeAll(): Flow<List<NoteEntity>>
    suspend fun upsertAll(notes: List<NoteEntity>)
}
data class NoteEntity(val id: Int, val title: String, val done: Boolean)
fun NoteDto.toEntity() = NoteEntity(id, title, done)

Discussion

No questions on this topic yet. Sign in to ask the first one.