Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 104 ยท App Architecture

The Repository Pattern and Data Sources

Learn the repository pattern in Android: a single source of truth, local and remote data sources, mappers between layers, caching strategies and fakes for testing.

Almost every app shows data that lives somewhere else: on a server, in a database, in a file or in a sensor. If every screen talked to Retrofit and Room directly, the same fetching, parsing, caching and error code would be copied into every ViewModel, and changing the server or the database would mean rewriting the whole app. A repository is the one class that hides this. The rest of the app asks it for data and does not care where the data came from.

In this lesson you will split the data layer into a repository and two data sources (local and remote), convert between three kinds of model classes with mappers, add a cache with a freshness rule, and replace the whole thing with a fake for tests. Retrofit and Room get their own lessons later, so the real Android pieces here are read-only sketches, and the TryIts are plain Kotlin stand-ins that run on the site. They use the same shape, only with in-memory data instead of real I/O. This lesson builds on Architecture Layers and StateFlow and collectAsStateWithLifecycle.

What a repository does

A repository sits between the ViewModel and the places where data lives. Its job is small and clear:

  • It exposes data in the form the rest of the app wants: domain models, Flows and suspend functions, never HTTP responses or database cursors.
  • It decides where to read from and write to: the network, the database, a memory cache, or a combination.
  • It maps errors and models so callers see one consistent vocabulary.
  • It hides threading: its functions are safe to call from the main thread because they switch dispatchers inside.
flowchart LR
    VM["ViewModel"] --> R["ArticleRepository"]
    R --> L["LocalDataSource<br/>(Room DAO)"]
    R --> N["RemoteDataSource<br/>(Retrofit API)"]
    N -. "network" .-> S[("Server")]
    L -. "SQLite" .-> D[("Database")]

The ViewModel depends on the repository only. The two data sources are details behind it.

A data source is a thin wrapper around one origin of data. A remote data source turns a function call into an HTTP request; a local data source turns it into a query. Neither of them knows about the other. Only the repository combines them, which is why the repository is the right place for rules such as "show the database first, then refresh".

You do not have to create a data source class for every case. A tiny app can call a Room DAO or a Retrofit interface straight from the repository. Add the extra layer when it earns its place: when the same source is used by several repositories, or when you want to fake it separately in tests.

A single source of truth

The most useful rule for a data layer is: for each kind of data, exactly one place owns it, and everything else reads from that place. That owner is the single source of truth. Often it is the local database: the network never feeds the UI directly, it only writes into the database, and the UI observes the database.

Why is that better than showing the network response directly?

  • The screen works offline, because it only reads local data.
  • Two screens showing the same article cannot disagree, because both read the same rows.
  • Rotation, process death and slow networks do not matter: the data is already stored.
  • Refreshing becomes simple: fetch, write, and every observer updates by itself.

The flow looks like this: the repository exposes a Flow of articles from the database. A refresh() function fetches from the server and replaces the database rows. Because the database emits a new list whenever its table changes, the UI redraws without anyone passing the response around.

sequenceDiagram
    participant UI as ViewModel
    participant Repo as Repository
    participant DB as Local source
    participant API as Remote source
    UI->>Repo: observe articles
    Repo->>DB: read as Flow
    DB-->>UI: old rows (instantly)
    UI->>Repo: refresh()
    Repo->>API: fetchArticles()
    API-->>Repo: DTO list
    Repo->>DB: replace rows
    DB-->>UI: new rows

The UI never sees the network response; it only sees what the database emits.

Three models, two mappers

Different layers need different shapes of the same data, and mixing them causes bugs.

  • DTO (data transfer object): matches the JSON from the server, field for field. It may have nullable fields and awkward names because the server decides them.
  • Entity: matches a database table. It is shaped for queries and storage.
  • Domain model (or UI model): what the app logic and screens use. It has the types you want: non-null titles, an enum instead of a magic string, a ready-to-show flag.

Small extension functions map one into the next, and they live next to the classes they convert:

Kotlin
// read-only sketch of the real layers
@Serializable
data class ArticleDto(
    val id: Int,
    val headline: String? = null,
    @SerialName("published_at") val publishedAt: String,
)

@Entity(tableName = "articles")
data class ArticleEntity(
    @PrimaryKey val id: Int,
    val title: String,
    val publishedAt: String,
)

fun ArticleDto.toEntity() = ArticleEntity(id, headline ?: "(untitled)", publishedAt)
fun ArticleEntity.toDomain() = Article(id, title, publishedAt)

Why not use one class everywhere? If the server renames a field, only the DTO and one mapper change. If you add a database index, only the entity changes. The UI code never notices. The cost is a few lines of mapping, which is cheap compared to the coupling it removes. Mapping is also the place to repair bad data, for example replacing a missing headline with a default, as above.

The first TryIt is a runnable stand-in with the same structure: an interface for the repository, two data sources behind interfaces, mappers, and a fake repository that a ViewModel test could use instead.

Kotlin Repository, data sources and mappers (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that ArticlesViewModel compiles against ArticleRepository only. That is the practical payoff: tests inject FakeArticleRepository, the app injects the real one, and the ViewModel code is identical. Dependency Injection Concepts shows how the real objects get wired together.

Caching and refresh strategies

Network calls are slow and cost battery and data, so repositories usually decide when to hit the network at all. Common strategies:

Strategy Behavior Good for
Network only Always fetch; no storage Data that must be current (a payment status)
Cache first Return stored data; fetch only if missing Rarely changing data (country list)
Cache then refresh Show stored data now, fetch in the background, update when it arrives Feeds, inboxes, most lists
Time-based (TTL) Fetch only when stored data is older than N minutes Weather, prices
Manual refresh Fetch when the user pulls to refresh Anything the user may want to force

A TTL needs a timestamp of the last successful refresh. Store it with the data, in the database or in DataStore, so it also survives process death. In tests, never read the system clock directly: pass a clock in, so you can move time forward on demand.

Failure matters as much as success. If a refresh fails, keep the old data and report the error, instead of wiping the screen. Whether a failure is shown as a snackbar or as a banner is a UI decision, so the repository should return or throw something the ViewModel can turn into UI state. The details are in Error Handling and Offline-first.

The second TryIt implements cache-then-refresh with a time-to-live, a fake clock and a remote source that fails on the third call. An observer collects the repository's StateFlow, standing in for what a ViewModel and a Compose screen would do with Room's Flow.

Kotlin A cache with a time-to-live and refresh (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read the output from top to bottom: the first open fetches, the reopen at 30 seconds is skipped, the one at 90 seconds fetches again, the forced refresh at 95 seconds is the third network call and fails, and the UI keeps showing the old items because the failure never touched the store. The next forced refresh succeeds and the observer receives the new list.

Interfaces, fakes and where logic belongs

Define the repository as an interface when more than one implementation is plausible: the real one, a fake for tests, a demo-mode one. A fake is a small, honest implementation with in-memory data. It is almost always better than a mocking library for repositories, because it behaves like the real thing (it remembers what you saved) and tests read like plain code. See Unit Testing ViewModels and Flows.

A few rules keep the data layer healthy:

  • Repositories hold data logic, ViewModels hold UI logic. "Is this cached copy too old?" belongs in the repository. "Show a spinner while loading" belongs in the ViewModel.
  • No Android types in the interface. No Context, no Uri, no Cursor. That keeps it testable on the JVM.
  • Expose Flow for data that changes over time and suspend functions for one-shot actions such as refresh() or save(note).
  • Be main-safe. A caller must never need to know that refresh() does disk or network work. Inside, use withContext(Dispatchers.IO), as you will see in Coroutines on Android.
  • Do not share mutable state outside: expose StateFlow, Flow or immutable lists, not MutableStateFlow or MutableList.
Kotlin
// read-only sketch: the real repository with Room as the source of truth
class OfflineFirstArticleRepository(
    private val api: ArticleApi,
    private val dao: ArticleDao,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
) : ArticleRepository {

    override val articles: Flow<List<Article>> =
        dao.observeAll().map { rows -> rows.map { it.toDomain() } }

    override suspend fun refresh() = withContext(ioDispatcher) {
        val dtos = api.getArticles()
        dao.replaceAll(dtos.map { it.toEntity() })
    }
}

Common mistakes

  • Returning DTOs or entities to the UI. The UI becomes tied to JSON field names and table layouts.
  • Keeping two sources of truth. Holding a list in memory and another copy in the database lets them drift apart. Pick one owner.
  • Clearing the cache before a fetch succeeds. If the request fails, the user is left with an empty screen. Replace the data only after you have new data in hand.
  • Creating repositories inside screens. A repository created per screen has no shared cache. Create it once and inject it.
  • Reading the system clock inside the repository. It makes TTL logic impossible to test.
  • A repository that grows into a god class. Split by data type (articles, users, settings), not by screen.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does it mean for the database to be the single source of truth?

    With one owner, all screens read the same rows, the app works offline, and a refresh simply updates the database so every observer redraws.
  2. 2. Why have separate DTO, entity and domain classes?

    Each layer changes for its own reasons. Mappers localize the damage when the server renames a field or you restructure a table, and they are the place to repair bad data.
  3. 3. A refresh request fails. What should a well-behaved repository do with the data already shown?

    Old data is usually more useful than a blank screen. Report the failure as a value or exception, and let the UI decide how to show it.
  4. 4. Why define the repository as an interface?

    The ViewModel depends on the interface only, so tests can supply a small in-memory fake while the app supplies the real implementation.

Summary

  • A repository hides where data comes from and exposes domain models, Flows and suspend functions to the rest of the app.
  • Data sources wrap one origin each (network, database); only the repository combines them.
  • Prefer a single source of truth, usually the local database: the network writes into it, the UI observes it.
  • DTOs, entities and domain models are separate, connected by small mapper functions.
  • Choose a caching strategy deliberately (cache then refresh, TTL, manual) and keep old data when a refresh fails.
  • Define repositories as interfaces and test with fakes; make them main-safe and keep Android types out of them.
  • Retrofit and Room code here is read-only; the TryIts are in-memory stand-ins with the same structure.

Next: Coroutines on Android