Single source of truth
Why it matters
- Google's "Build an offline-first app" guide makes the local data source the canonical source of truth. Every offline-first design starts from this rule.
- When the UI shows network responses directly, two screens (or a screen and a background sync) can show different data for the same item. Reading only from Room removes that class of bug.
- The screen shows saved data immediately, even with no connection, instead of a spinner or an empty list while the first network call runs.
- Interviewers use this topic to check whether you can trace data through the repository, Room,
Flowand the ViewModel, not just call a Retrofit API.
The simple explanation
- A restaurant kitchen where the chef only cooks from the ticket rail.
- Waiters (the network) can add or change tickets, but a change only counts once it is written on the rail.
- The dining room display (the UI) only shows what is on the rail.
- If the waiters cannot reach the kitchen, the chef keeps cooking from the tickets already there.
What is a single source of truth in Android? It is one owner for a piece of data that every reader observes. In an offline-first app that owner is the local database (usually Room): the UI observes a Flow from the database, and the network is only used to update the database. Google's guide puts it this way: the local data source should be the exclusive source of any data that higher layers read.
The repository owns both data sources. Its read APIs return Flows backed by Room. When a refresh succeeds, the repository writes the result into Room, Room re-runs the observed queries, and every collector gets the new data. If the refresh fails, nothing in the database changes, so the screen keeps showing the last saved data.
| Component | Role |
|---|---|
| UI (Compose or Views) | Collects UI state from the ViewModel |
| ViewModel | Turns the repository Flow into a StateFlow with stateIn |
| Repository | Exposes Flow reads from Room; fetches from the network and writes the result into Room |
| Local data source (Room) | The source of truth that every read comes from |
| Network data source (Retrofit) | Only used by the repository to update Room, never read by the UI |
Writes follow the same rule. For data the user creates offline, the repository writes to Room first and syncs to the server later (the guide calls this a lazy write; see the Queued writes with WorkManager lesson). That means a refresh must not blindly overwrite rows that still have unsynced local changes.
Google's guide also recommends separate models: a network model (NetworkUser), a Room entity (UserEntity) and an external model (User) that the rest of the app uses, with small mapping functions between them.
Notes
- The UI and domain layers never call the network directly. Only the repository talks to the network data source, and it uses the result to update Room.
- DAO reads return
Flow(for exampleFlow<List<UserEntity>>). Room re-emits whenever a table the query reads from changes, whoever wrote it: the repository, aWorkManagerworker or another screen. - In the ViewModel, convert the repository
FlowwithstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initialValue)and collect it in Compose withcollectAsStateWithLifecycle(). - Writes are
suspendfunctions. Room and Retrofit suspend functions are already main-safe, so the repository does not needwithContext(Dispatchers.IO)around them. - A failed refresh leaves the database unchanged, so the screen keeps the cached data. Report the failure as a separate piece of UI state (for example an "offline" banner), not by clearing the list.
- Keep network models and Room entities inside the data layer and expose a plain model to the rest of the app.
@Upsertinserts new rows and updates existing ones, but it does not delete rows the server removed. Delete those explicitly in the same@Transactionif the list must match the server.- A ViewModel that keeps its own copy of business data in a
MutableStateFlowcreates a second source of truth. Keep only screen state (input text, selection, an error flag) in the ViewModel. - When catching refresh errors in a coroutine, catch
IOExceptionandHttpExceptionrather thanException, soCancellationExceptionis not swallowed.
Code example
An offline-first repository with Room and Retrofit: reads come only from the DAO Flow, and a refresh writes network data into Room. The ViewModel turns the stream into UI state and reports refresh failures separately.
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Upsert
import java.io.IOException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
import retrofit2.HttpException
import retrofit2.http.GET
@Entity(tableName = "users")
data class UserEntity(
@PrimaryKey val id: String,
val name: String,
)
@Serializable
data class NetworkUser(val id: String, val name: String)
data class User(val id: String, val name: String)
fun NetworkUser.asEntity() = UserEntity(id = id, name = name)
fun UserEntity.asExternalModel() = User(id = id, name = name)
@Dao
interface UserDao {
@Query("SELECT * FROM users ORDER BY name")
fun observeUsers(): Flow<List<UserEntity>>
@Upsert
suspend fun upsertAll(users: List<UserEntity>)
}
interface UserApi {
@GET("users")
suspend fun fetchUsers(): List<NetworkUser>
}
class OfflineFirstUserRepository(
private val userDao: UserDao,
private val api: UserApi,
) {
// The only read API: it comes from Room, never from the network
fun observeUsers(): Flow<List<User>> =
userDao.observeUsers().map { rows -> rows.map { it.asExternalModel() } }
// The network only updates Room; Room then re-emits to every collector
suspend fun refresh() {
val remote = api.fetchUsers()
userDao.upsertAll(remote.map { it.asEntity() })
}
}
class UsersViewModel(private val repository: OfflineFirstUserRepository) : ViewModel() {
val users: StateFlow<List<User>> = repository.observeUsers()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
private val _refreshFailed = MutableStateFlow(false)
val refreshFailed: StateFlow<Boolean> = _refreshFailed.asStateFlow()
init { refresh() }
fun refresh() {
viewModelScope.launch {
_refreshFailed.value = try {
repository.refresh()
false
} catch (e: IOException) {
true
} catch (e: HttpException) {
true
}
}
}
}observeUsers()is the only read path. The new list reaches the UI because Room re-emits afterupsertAll, not becauserefresh()returns anything.- A failed refresh only flips
refreshFailed; the cached list stays on screen. - Catching
IOExceptionandHttpException(notException) keeps coroutine cancellation working.
Run the idea in plain Kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.io.IOException
data class User(val id: Int, val name: String)
// Stands in for a Room DAO: a table whose observers get every change
class FakeUserDao {
private val table = MutableStateFlow<List<User>>(emptyList())
fun observeUsers(): Flow<List<User>> = table
fun upsertAll(users: List<User>) {
val byId = table.value.associateBy { it.id }.toMutableMap()
users.forEach { byId[it.id] = it }
table.value = byId.values.sortedBy { it.id }
}
}
class FakeApi(var online: Boolean) {
fun fetchUsers(): List<User> {
if (!online) throw IOException("offline")
return listOf(User(1, "Alice"), User(2, "Bob"))
}
}
class Repository(private val dao: FakeUserDao, private val api: FakeApi) {
fun observeUsers(): Flow<List<User>> = dao.observeUsers()
fun refresh() = dao.upsertAll(api.fetchUsers())
fun rename(id: Int, name: String) = dao.upsertAll(listOf(User(id, name)))
}
fun main() = runBlocking {
val dao = FakeUserDao()
dao.upsertAll(listOf(User(1, "Alice (cached)")))
val api = FakeApi(online = false)
val repo = Repository(dao, api)
val ui = launch {
repo.observeUsers().collect { users -> println("UI shows: " + users.map { it.name }) }
}
yield()
try {
repo.refresh()
} catch (e: IOException) {
println("Refresh failed (" + e.message + "), cached data stays")
}
yield()
api.online = true
repo.refresh()
yield()
repo.rename(2, "Bobby")
yield()
ui.cancel()
}Expected output:
UI shows: [Alice (cached)]
Refresh failed (offline), cached data stays
UI shows: [Alice, Bob]
UI shows: [Alice, Bobby]
In production
- Users renamed themselves on the profile screen, saw the new name, then saw the old name return a moment later.
- The ViewModel held the profile in its own
MutableStateFlow, set it from the API response, and also collected the RoomFlow. - A background sync wrote an older copy of the profile into Room, Room emitted it, and the ViewModel overwrote its in-memory value with the stale one.
- Removed the ViewModel's own copy of the profile; the screen state is now
repository.observeProfile().stateIn(...). - The rename writes to Room first (marked as pending sync), and the server call happens from the sync path.
- The sync now skips rows that still have pending local changes, so an older server copy cannot overwrite a newer local edit.
Common mistakes
- Showing the network response directly in the UI. The screen is empty offline and can disagree with other screens that read Room. Write the response to Room and observe Room.
- Updating UI state by hand after a network call. The ViewModel and the database become two sources of truth that drift apart. Let the Room
Flowdeliver the change. - One-shot DAO reads for screen data. A
suspend fun getUsers(): List<UserEntity>does not update when a worker or another screen changes the table. ReturnFlowfor anything the UI shows. - Using one model for the API, the database and the UI. A backend field rename then breaks Room schemas and screens at once. Keep separate network, entity and external models with mappers.
- Clearing cached data when a refresh fails. The user loses data they could have used offline. Keep the cache and show the error alongside it.
- Refresh overwriting unsynced local edits. An upsert from the server replaces a row the user just changed offline. Skip or merge rows that are still pending sync.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is a single source of truth in an offline-first Android app?”
“A refresh succeeds on the network but the database write fails. What happens and how do you handle it?”
“Why shouldn't the ViewModel hold business data in its own MutableStateFlow?”
“How do you show cached data immediately and still keep it fresh?”
Quiz
In an offline-first app, what should the UI observe to always show the latest saved data?
What is the repository's job in this pattern?
The repository fetches new data from the network but forgets to write it to Room. What does the UI show?
A refresh fails because the device is offline. The database holds cached data. What should the screen do?
0 of 4 answered
Mini task
Task: build a single source of truth repository
Goal: a repository where the UI only ever reads from the local "database".
- Model: create
data class TaskEntity(val id: Int, val title: String). - Fake DAO: create a
TaskDaointerface withfun observeTasks(): Flow<List<TaskEntity>>andsuspend fun upsertAll(tasks: List<TaskEntity>). Implement it with aMutableStateFlowthat plays the role of the Room table. - Repository:
TaskRepository(dao, api)exposesval tasks: Flow<List<TaskEntity>> = dao.observeTasks()andsuspend fun refresh(), which callsapi.fetchTasks()and writes the result withdao.upsertAll.refresh()returns nothing. - Failure: give the fake API an
onlineflag that makesfetchTasks()throwIOException. Catch onlyIOExceptionwhere you callrefresh(). - Run it: in
mainwithrunBlocking, collecttasksin alaunch, callrefresh()once offline and once online.
Done condition: the collector prints the initial list, nothing changes after the offline refresh except an error message, and the new list prints after the online refresh without any second subscription or manual UI update.