Repository pattern

Learn the Android Repository pattern to manage Room, Retrofit, and DataStore, mapping models to provide a single source of truth for ViewModels. About 25 minutes.

Why it matters

  • The ViewModel should not import a DAO or a Retrofit interface; the Repository hides them, so changing a data source touches the data layer, not every screen.
  • Without a single source of truth, a ViewModel that writes to Room and calls Retrofit separately can overwrite a fresh local edit with a stale network response, a bug that is hard to reproduce.
  • Interviewers at mid and senior levels ask you to draw the data flow and explain where mapping happens; a wrong answer (mapping in the ViewModel, exposing entities to Compose) signals a shallow architecture.
  • Testing becomes straightforward: give the Repository a fake DAO and a fake API, and assert on the Flow output without a real database or network. ViewModels get a fake Repository.

The simple explanation

  • A restaurant has one pass where finished plates come out (the Repository). Waiters never walk into the walk-in fridge (Room) or call the supplier (the network); they take what the pass gives them.
  • The kitchen keeps the fridge stocked from the supplier. What goes out is always what is in the fridge, so every waiter sees the same thing (single source of truth).

The Repository pattern places one class between the data sources (Room, Retrofit, DataStore) and the rest of the app (ViewModels, use cases). It is the entry point for one type of data: the ViewModel collects from the Repository and never touches a DAO, a network client, or a preferences file directly. Each type of data has one single source of truth (SSOT): one place that owns it and is the only place it changes. In an offline-first app that is the database: network results are written into Room, and the Repository exposes what Room emits.

The core mechanism has three parts:

  • Abstraction. The Repository defines an interface (ArticleRepository) with methods like observeAll(): Flow<List<Article>> and suspend fun refresh(). The implementation (ArticleRepositoryImpl) injects a Room DAO and a Retrofit API. Swapping the data source means changing the implementation, not the ViewModel.

  • Mapping. Three model types exist: the DTO (deserialized from JSON, e.g. ArticleDto), the Room entity (mapped to a table, e.g. ArticleEntity), and the domain model (what the UI sees, e.g. Article). Mapping functions (toDomain(), toEntity()) live in the data layer, next to the Repository or in a mapper file. This keeps entity schema changes and API changes from leaking into the UI. Small apps sometimes use one model for all three; the split pays off once the API, the table and the UI start to differ.

  • Strategy. The Repository decides when to read local and when to hit the network. A common offline-first flow: expose dao.observeAll() as a Flow so the UI renders cached data instantly; call refresh() to fetch new data and upsert it into Room, which re-emits the Flow. The UI never waits on the network for data it already has. Writes go to Room first and are synced to the server afterwards (often with WorkManager), so a refresh must not overwrite local edits that have not been synced yet.

LayerType exampleWho sees it
NetworkArticleDtoRepository only
Local (Room)ArticleEntityRepository only
DomainArticleViewModel, Compose

Threading. Repository functions should be main-safe. Room suspend DAO functions and Flow queries, and Retrofit suspend functions, already run off the main thread, so they need no withContext. Use withContext with an injected dispatcher only for blocking or CPU-heavy work, such as mapping a very large list or reading a file.

When Room is the cache, the Repository keeps no second in-memory copy of the same data. A Repository without a database can keep a small in-memory cache, guarded by a Mutex. It performs no UI logic. In a Paging 3 setup the Repository builds the Pager (with a PagingSource and, for network plus database, a RemoteMediator) and returns Flow<PagingData<T>>; the ViewModel applies cachedIn(viewModelScope) and the UI calls collectAsLazyPagingItems(). A DataStore setting can be read inside the Repository when the domain model needs it, but the ViewModel still sees only the domain type.

The repository decides where data comes from
The repository decides where data comes from The ViewModel collects a Flow of Article from ArticleRepository and calls refresh; the repository observes the Room DAO and maps each ArticleEntity to Article, and on refresh fetches ArticleDto objects from the Retrofit API and upserts them into Room, which makes the Flow emit again. refresh() Flow<Article> observeAll() UPSERT FETCH ViewModel only sees Article ArticleRepository maps with toDomain() Room DAO ArticleEntity Retrofit API ArticleDto
The ViewModel only sees Article; the repository reads Room, writes network results into it, and maps entities and DTOs.

Notes

  • The Repository is the entry point for its data; the ViewModel collects from it and never calls a DAO or a network client directly. In offline-first, Room is the single source of truth and the Repository exposes it.
  • Expose Flow<DomainModel> from the Repository for data that changes over time, and suspend functions for one-shot operations. Do not expose Flow<Entity> or Flow<Dto>, so schema or API changes stay inside the data layer.
  • Mapping functions (toDomain(), toEntity()) live in the data layer, in the Repository or a dedicated mapper file, not inside the ViewModel or the Composable.
  • When Room is the cache, do not keep a second MutableList copy in the Repository; Room's Flow queries re-emit when the table changes. Without a database, a small in-memory cache guarded by a Mutex is fine.
  • The Repository decides the strategy: offline-first (read from Room, refresh into Room in the background, write locally then sync) or online-only (call the network each time, maybe with a short in-memory cache).
  • @Upsert in Room makes refresh() idempotent: the same primary key overwrites the row, a new key inserts it, so calling refresh twice is safe.
  • Room Flow queries re-emit whenever a table they read is written (even with identical data, so add distinctUntilChanged() if that matters), so after upsert the UI updates without a manual reload.
  • Repository functions are main-safe. Room and Retrofit suspend functions already are; add withContext(injectedDispatcher) only around blocking or CPU-heavy work.
  • For unit testing, give the Repository a fake DAO (or an in-memory Room database) and a fake API, and test its real logic. ViewModel tests use a fake Repository.
  • Google's guidance is one Repository per type of data. Splitting UserListRepository, UserDetailRepository and UserSearchRepository over one table spreads the rules for that data across classes; one UserRepository with different methods is usually enough.

Code example

This shows a domain model, a Room entity, a network DTO, and a Repository that maps between them and exposes a Flow of domain objects. The ViewModel would collect that Flow and never see an entity or a DTO.

import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Upsert
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import retrofit2.http.GET
 
// Domain model: the only type the UI layer sees
data class Article(val id: Long, val title: String, val body: String)
 
// Network DTO (field names follow the API)
data class ArticleDto(val id: Long, val title: String, val content: String)
 
// Room entity: one row in the articles table
@Entity(tableName = "articles")
data class ArticleEntity(
    @PrimaryKey val id: Long,
    val title: String,
    val body: String,
)
 
@Dao
interface ArticleDao {
    @Query("SELECT * FROM articles ORDER BY id")
    fun observeAll(): Flow<List<ArticleEntity>>
 
    @Upsert
    suspend fun upsertAll(articles: List<ArticleEntity>)
}
 
interface ArticleApi {
    @GET("articles")
    suspend fun fetchArticles(): List<ArticleDto>
}
 
// Repository interface: the ViewModel depends on this, not on DAO or API
interface ArticleRepository {
    fun observeAll(): Flow<List<Article>>
    suspend fun refresh()
}
 
class ArticleRepositoryImpl(
    private val dao: ArticleDao,
    private val api: ArticleApi,
) : ArticleRepository {
 
    // Offline-first: Room is the source of truth and re-emits on every write
    override fun observeAll(): Flow<List<Article>> =
        dao.observeAll().map { entities -> entities.map { it.toDomain() } }
 
    // Fetch from network, upsert into Room; the Flow above re-emits.
    // Both calls are main-safe suspend functions, so no withContext is needed.
    override suspend fun refresh() {
        val dtos = api.fetchArticles()
        dao.upsertAll(dtos.map { it.toEntity() })
    }
}
 
// Mappers keep entity and DTO out of the UI layer
fun ArticleEntity.toDomain() = Article(id = id, title = title, body = body)
fun ArticleDto.toEntity() = ArticleEntity(id = id, title = title, body = content)
  • observeAll() returns a Flow of domain models, not entities, so renaming or adding a column in ArticleEntity does not reach the ViewModel.
  • refresh() writes into Room instead of returning data, so there is exactly one path to the UI: the database. If it throws (no network), the cached list stays on screen and the caller turns the error into UI state.
  • @Upsert inserts new ids and updates existing ones, so calling refresh() twice is safe.
  • The two mapper extension functions are the only place where DTO field names (content) and entity column names (body) are reconciled.

Run the idea in plain Kotlin

A fake "table" built on MutableStateFlow stands in for Room: every write re-emits to observers. The repository maps remote and cached models to a domain model, and the observer (playing the ViewModel) only ever sees Product.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

data class Product(val id: Int, val name: String, val price: Double) // domain
data class ProductDto(val id: Int, val title: String, val cost: Double) // network
data class ProductEntity(val id: Int, val name: String, val price: Double) // database

class FakeProductDao {
  private val table = MutableStateFlow<Map<Int, ProductEntity>>(emptyMap())

  fun observeAll(): Flow<List<ProductEntity>> = table.map { rows -> rows.values.sortedBy { it.id } }

  suspend fun upsertAll(items: List<ProductEntity>) {
      table.update { rows -> rows + items.associateBy { it.id } }
  }
}

class FakeProductApi {
  var prices = listOf(9.99, 19.99)
  suspend fun fetchAll(): List<ProductDto> {
      delay(100)
      return listOf(ProductDto(1, "Widget", prices[0]), ProductDto(2, "Gadget", prices[1]))
  }
}

fun ProductEntity.toDomain() = Product(id, name, price)
fun ProductDto.toEntity() = ProductEntity(id, title, cost)

class ProductRepository(private val dao: FakeProductDao, private val api: FakeProductApi) {
  fun observeAll(): Flow<List<Product>> = dao.observeAll().map { rows -> rows.map { it.toDomain() } }

  suspend fun refresh() {
      dao.upsertAll(api.fetchAll().map { it.toEntity() })
  }
}

fun main() = runBlocking {
  val api = FakeProductApi()
  val repo = ProductRepository(FakeProductDao(), api)
  val ui = launch {
      repo.observeAll().collect { products -> println("UI got " + products) }
  }
  yield()
  repo.refresh() // first sync fills the table
  yield()
  api.prices = listOf(8.99, 19.99)
  repo.refresh() // same ids: upsert updates the rows
  yield()
  ui.cancel()
}

Expected output:

UI got []
UI got [Product(id=1, name=Widget, price=9.99), Product(id=2, name=Gadget, price=19.99)]
UI got [Product(id=1, name=Widget, price=8.99), Product(id=2, name=Gadget, price=19.99)]

In production

Entity leaked into Compose
  • The team passed Room ArticleEntity objects straight into @Composable functions and previews.
  • A migration renamed the body column to content to match the API, and the property was renamed with it.
  • Dozens of Composables, previews and UI tests stopped compiling, because the database schema had become the UI contract.
The fix
  • Introduced an Article domain model with only the fields the UI needs.
  • Added toDomain() mappers in the data layer so the ViewModel and Compose layer see only Article.
  • Moved the entities into a data module and made them internal, so the compiler now stops any *Entity from being used in a feature module.
A refresh overwrote a local edit
  • A notes screen's ViewModel wrote edits straight to the DAO and, separately, launched a full refresh() every time the screen opened.
  • When a user edited a note while offline and reopened the screen just after reconnecting, the refresh fetched the server's older copy and upserted it over the local edit before the edit was ever sent.
  • Users saw their changes disappear a moment later; support tickets spiked.
The fix
  • All writes moved into NoteRepository.edit(), which saves the row in Room with a pendingSync = true flag and schedules a WorkManager job to send it to the server.
  • refresh() now skips rows that still have pendingSync = true, so server data cannot overwrite an unsynced edit. The sync job clears the flag after the server accepts the change.
  • A Repository test with a fake DAO and a fake API edits a note, runs a refresh that returns the old copy, and asserts the edit is still there.

Common mistakes

  • Exposing Room entities to the ViewModel. Any schema change (new column, renamed field) forces a change in every Composable that reads the entity. Map to a domain model inside the Repository so the UI contract is stable.
  • ViewModel calls DAO and Retrofit directly. Each screen re-implements the caching rules, and two coroutines can write the same row in any order, producing stale data. The Repository is the one place that decides how network data and local edits are combined.
  • Repository keeps its own copy of Room data. A MutableList next to a Room table duplicates the cache and drifts out of sync when another part of the app writes to the table. Expose Room's Flow instead.
  • Mapping DTO to entity inside the ViewModel. The ViewModel now depends on the network shape. If the API renames a field, the ViewModel breaks. Mapping belongs in the data layer.
  • Multiple repositories for one entity. UserListRepository and UserDetailRepository can hold different cached copies of the same user. Use one UserRepository with observeList() and observeById(id) methods.
  • Wrapping Room and Retrofit calls in withContext(Dispatchers.IO) everywhere. Their suspend functions are already main-safe, so the extra switch adds noise, and a hard-coded dispatcher cannot be replaced in tests. Inject a dispatcher and use it only for blocking or CPU-heavy work.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Why not call the Room DAO directly from the ViewModel?”

“How does the Repository handle offline-first?”

“What should the Repository expose to the ViewModel, and when is a suspend function right?”

“How would you unit-test a Repository that combines Room and Retrofit?”

Quiz

What type should the Repository expose to the ViewModel for a list that changes over time?

Where should the mapping from a network DTO to a Room entity happen?

In an offline-first Repository, what is the single source of truth for the data the UI shows?

A Repository's refresh() calls a Retrofit suspend function and a Room @Upsert suspend function. Does it need withContext(Dispatchers.IO)?

0 of 4 answered

Mini task

Build a ProductRepository in 15 minutes

  1. Create a domain model data class Product(val id: Long, val name: String, val price: Double) in a domain package.

  2. Create a Room entity @Entity(tableName = "products") data class ProductEntity with @PrimaryKey val id: Long, val name: String, val price: Double in a data.local package. Add a ProductDao with @Query("SELECT * FROM products") fun observeAll(): Flow<List<ProductEntity>> and @Upsert suspend fun upsertAll(items: List<ProductEntity>).

  3. Create a DTO data class ProductDto(val id: Long, val title: String, val cost: Double) in a data.remote package. Note the different field names: title vs name, cost vs price.

  4. Write two extension functions: ProductEntity.toDomain() and ProductDto.toEntity() in a mappers.kt file.

  5. Define an interface ProductRepository with fun observeAll(): Flow<List<Product>> and suspend fun refresh(). Implement it as ProductRepositoryImpl that injects ProductDao and a ProductApi (a Retrofit interface with suspend fun fetchAll(): List<ProductDto>). In observeAll(), map the DAO Flow through toDomain(). In refresh(), call the API, map DTOs to entities, and call dao.upsertAll().

  6. In a ProductViewModel, inject ProductRepository and expose val products: StateFlow<List<Product>> = repository.observeAll().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()). Call refresh() from init inside viewModelScope.launch, catching errors into UI state.

  7. Done condition: the ProductViewModel file does not import any class from data.local or data.remote. If you rename a column in ProductEntity or a field in ProductDto, the ViewModel and any Composable that uses Product do not need to change.

Next: Paging 3