An offline-first Android app treats the local database as the source of truth. The network is a synchronization channel, not the place the UI reads from. Room holds the data the user can already see; WorkManager retries the uploads and downloads when the radio comes back.

Local source of truth, then sync

Advertisement

This post uses only APIs that have been stable for years: Room, Flow, and CoroutineWorker. It does not invent a "Room Sync" product. (Jetpack's DataStore and WorkManager are the primitives; some teams add a custom sync engine or a library such as SQLDelight on other platforms, but the pattern below is the one most Android codebases already have.)

The rule

plaintext
UI  →  ViewModel  →  Repository  →  Room
                                ↘  WorkManager  →  API

The UI never calls the network for a list it already has. It collects a Flow from Room. A refresh enqueues work. When that work succeeds, it writes to Room, and the Flow emits.

kotlin
@Dao
interface NoteDao {
    @Query("SELECT * FROM notes ORDER BY updatedAt DESC")
    fun observeAll(): Flow<List<NoteEntity>>

    @Upsert
    suspend fun upsertAll(notes: List<NoteEntity>)

    @Query("SELECT * FROM notes WHERE dirty = 1")
    suspend fun dirty(): List<NoteEntity>
}

class NoteRepository(
    private val dao: NoteDao,
    private val workManager: WorkManager,
) {
    fun observeNotes(): Flow<List<Note>> =
        dao.observeAll().map { rows -> rows.map { it.toModel() } }

    fun requestSync() {
        val request = OneTimeWorkRequestBuilder<NoteSyncWorker>()
            .setConstraints(
                Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build(),
            )
            .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, TimeUnit.SECONDS)
            .build()
        workManager.enqueueUniqueWork(
            "note-sync",
            ExistingWorkPolicy.KEEP,
            request,
        )
    }

    suspend fun saveLocal(note: Note) {
        dao.upsertAll(listOf(note.toEntity(dirty = true)))
        requestSync()
    }
}

ExistingWorkPolicy.KEEP avoids stacking a new worker every time the user taps Save. REPLACE is right when the latest request should preempt an old one.

The worker

CoroutineWorker is the coroutine-friendly WorkManager primitive. Do the I/O in doWork(), and return Result.retry() when a transient network error should come back later.

kotlin
class NoteSyncWorker(
    appContext: Context,
    params: WorkerParameters,
    private val dao: NoteDao,
    private val api: NoteApi,
) : CoroutineWorker(appContext, params) {

    override suspend fun doWork(): Result {
        return try {
            // Push local writes first so the server sees the latest edits.
            dao.dirty().forEach { note ->
                api.putNote(note.toDto())
                dao.upsertAll(listOf(note.copy(dirty = false)))
            }
            // Then pull the remote snapshot (or a delta if your API has one).
            val remote = api.listNotes()
            dao.upsertAll(remote.map { it.toEntity(dirty = false) })
            Result.success()
        } catch (e: IOException) {
            Result.retry()
        } catch (e: HttpException) {
            if (e.code() in 500..599) Result.retry() else Result.failure()
        }
    }
}

Inject the DAO and API with a WorkerFactory (Hilt's @HiltWorker is the usual approach). Do not grab singletons from applicationContext if you can avoid it.

Conflict handling, kept honest

If two devices edit the same row, last-write-wins on a updatedAt timestamp is the honest simple policy. Server-wins is also fine if the product says so. What you should not do is pretend you have automatic merge of free-form text without designing it.

A practical schema:

  • id (stable client- or server-issued)
  • updatedAt (ISO instant, set on every local edit)
  • dirty (true until the push succeeds)
  • optional deleted for tombstones, so a swipe-away can be pushed later

When the pull comes in, skip overwriting a row that is still dirty locally, or you will clobber an unsynced edit.

Why not "just Retrofit in the ViewModel"?

It works until the process is killed mid-upload, the user opens the app in a tunnel, or a list must show yesterday's data instantly. WorkManager survives process death, respects battery optimizations reasonably well, and gives you backoff and constraints (UNMETERED, charging) for free. Room survives process death by definition.

If your app is a short-lived form that must be online, a direct suspend call is still correct. Offline-first is for data the user should be able to read and edit on a train.

Start with Room as the only thing the UI observes, mark local edits dirty, and let a unique CoroutineWorker push and pull. That is a complete offline-first loop — no fictional sync framework required.