TL;DR
- In an offline-first app, the UI only ever reads from the local database, never straight from the network.
- Room + Flow make this easy: every write to Room automatically pushes fresh data to the screen.
- The network's only job is to keep Room up to date: pull new data in, push local changes out.
- Writes go to Room first and are marked pending. WorkManager syncs them when the connection comes back.
Open your app on a train, in a lift, or in airplane mode. Does it show a spinner forever? An error screen? Do changes just disappear? If so, your app is online-first, and your users feel it every day. Let's fix that with one idea: a single source of truth.
Prefer video?Offline-First Android App Development: course introduction
01 Feel the difference first
Below are two versions of the same task app. Go offline, add a few tasks, then reopen the app. Watch what happens to each one.
Online-first
Offline-first
The offline-first app never waits for the network, so it never loses work. Here's how to build it.
02 Why online-first breaks
Most apps start like this: the ViewModel calls the API, waits, and puts the result on screen.
class TasksViewModel(private val api: TaskApi) : ViewModel() {
var state by mutableStateOf<UiState>(UiState.Loading)
private set
init {
viewModelScope.launch {
state = try {
UiState.Success(api.fetchTasks()) // no network = no data
} catch (e: IOException) {
UiState.Error("Check your connection")
}
}
}
}
It looks clean, but it has three hidden problems:
- No network, no app. Every screen depends on a request succeeding.
- Two sources of truth. The screen holds one copy of the data, the server another, and maybe a cache a third. They drift apart.
- Lost writes. If saving a task fails, the user's work is simply gone.
03 The fix: a single source of truth
Flip the arrows around. The UI observes only the database. The network never talks to the UI. It only reads from and writes to the database.
The rule: if data is on the screen, it came from Room. No exceptions.
04 Step 1: the read path (Room + Flow)
Start with an entity that knows whether it has been synced, and a DAO that returns a Flow.
@Entity(tableName = "tasks")
data class TaskEntity(
@PrimaryKey val id: String, // generated on the device (UUID)
val title: String,
val isDone: Boolean,
val updatedAt: Long,
val pendingSync: Boolean = false, // true = changed locally, not on the server yet
)
@Dao
interface TaskDao {
@Query("SELECT * FROM tasks ORDER BY updatedAt DESC")
fun observeAll(): Flow<List<TaskEntity>>
@Query("SELECT * FROM tasks WHERE pendingSync = 1")
suspend fun pending(): List<TaskEntity>
@Upsert
suspend fun upsert(task: TaskEntity)
@Upsert
suspend fun upsertAll(tasks: List<TaskEntity>)
}
Because observeAll() returns a Flow, Room re-emits the list every time the table changes,
whether the change came from the user, a background sync, or anything else. You never "refresh the UI" by hand.
class TasksViewModel(private val repo: TaskRepository) : ViewModel() {
val tasks: StateFlow<List<Task>> = repo.tasks
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
init {
// Try to fetch fresh data, but the screen never waits for it.
viewModelScope.launch { runCatching { repo.refresh() } }
}
fun add(title: String) = viewModelScope.launch { repo.addTask(title) }
}
Notice what's missing: no loading flag blocking the screen and no error state for "offline". Cached data shows instantly.
05 Step 2: the write path (local first)
When the user creates or edits something, write it to Room immediately, mark it as pending, and ask for a sync.
class TaskRepository(
private val db: AppDatabase,
private val api: TaskApi,
private val sync: SyncScheduler,
) {
private val dao = db.taskDao()
// READ: the only data the UI ever sees
val tasks: Flow<List<Task>> = dao.observeAll().map { rows -> rows.map { it.toDomain() } }
// WRITE: save locally first, sync later
suspend fun addTask(title: String) {
dao.upsert(
TaskEntity(
id = UUID.randomUUID().toString(),
title = title,
isDone = false,
updatedAt = System.currentTimeMillis(),
pendingSync = true,
)
)
sync.requestSync()
}
// PULL: bring server data into Room, but never overwrite unsynced local edits
suspend fun refresh() {
val remote = api.fetchTasks()
db.withTransaction {
val pendingIds = dao.pending().map { it.id }.toSet()
dao.upsertAll(remote.filter { it.id !in pendingIds }.map { it.toEntity() })
}
}
// PUSH: send pending changes, then mark them as synced
suspend fun pushPending() {
dao.pending().forEach { task ->
api.upsertTask(task.toDto())
dao.upsert(task.copy(pendingSync = false))
}
}
}
The classic bug: a refresh that blindly overwrites rows will wipe out edits the user made offline. Always skip rows that are still pendingSync.
Generating IDs on the device (UUIDs) matters too: the task needs an identity before the server has ever seen it, so the UI and later updates can refer to it.
06 Step 3: sync in the background with WorkManager
Pending changes need to reach the server even if the user closes the app. That's exactly what WorkManager is for: it runs your work when constraints are met (like "has network") and retries with backoff if it fails.
@HiltWorker
class SyncWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val repo: TaskRepository,
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result = try {
repo.pushPending()
repo.refresh()
Result.success()
} catch (e: IOException) {
Result.retry() // network hiccup: WorkManager tries again later
}
}
class SyncScheduler(private val workManager: WorkManager) {
fun requestSync() {
val request = OneTimeWorkRequestBuilder<SyncWorker>()
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
.build()
// One sync chain at a time; new requests queue up behind a running one
workManager.enqueueUniqueWork("task-sync", ExistingWorkPolicy.APPEND_OR_REPLACE, request)
}
}
That's the whole loop: the user writes to Room, Room updates the UI instantly, WorkManager waits for a connection, pushes pending rows, pulls fresh data back into Room, and the UI updates again by itself.
07 Where it gets hard
The pattern above is the foundation. Real apps hit these next, and each one needs a deliberate design:
Conflicts Two devices edit the same task offline.
Who wins? Timestamps from device clocks can't be trusted. The usual answer is a server-controlled version number: each update says which version it was based on, so the server can detect stale writes.
Deletes A task is deleted on one device.
If you simply remove the row, other devices never find out. Instead, keep a tombstone (a soft-delete flag) so the deletion itself can be synced.
Scale Downloading everything on every sync.
Fine for 50 tasks, painful for 50,000. Use a cursor: the client remembers the last change it saw and asks only for what's new, like GET /sync?cursor=100.
Races The user edits a task while it's being pushed.
Marking it synced after the push could hide the newer edit. Compare updatedAt or the version before clearing pendingSync.
08 Your offline-first checklist
- The UI observes Room through a
Flow, never the API directly - Writes go to Room first, with a
pendingSyncflag - IDs are generated on the device
- Refreshes never overwrite pending local changes
- WorkManager pushes changes with a network constraint and backoff
- You have a plan for conflicts, deletes and incremental sync
Build the full system
Offline-First Android App
Go all the way: server versions, change logs, tombstones, cursor-based sync and multi-device conflicts, with your own Ktor backend instead of Firebase.
