The Repository Pattern
Android Development with Compose: Architecture & Data
Course 5 ยท Chapter 5 ยท One Door to the Data
Chapter 3 gave the ViewModel a fake repository and Chapter 4 gave you a real DAO. The repository joins them: a class the rest of the app talks to for notes, that decides where the notes come from. Today it hides Room; in Chapter 7 it will also hide a network call, and no screen will need to change.
Flow follows a getXxxStream naming pattern (for example getAuthorStream());
a repository maps internal data models to external ones inside a Flow map (shown in a codelab the docs now mark deprecated); for complex apps create a model per layer; and state holders should never have a data source as a direct dependency. General knowledge, not checked: the interface and fake design, the factory code, the unit test and the layer table.
All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install. The code assumes the Room 2.x form from Chapter 4.
What a Repository Is For
- One door. (docs) Data sources stay hidden behind the repository; ViewModels and use cases never depend on a data source directly.
- A single source of truth. (docs) The UI shows data from one place. With a local database that is the recommended source of truth for offline-first support, the pattern is: the network (Chapter 7) writes into the database, and the screen only ever reads from the database.
- Even for one data source. (docs) The recommendation to use repositories applies even when one wraps a single data source, as ours does today.
A Model for the UI, Separate From the Entity
(docs) For complex apps, the guidance is a model per layer. (general knowledge) Here the reason is simple: NoteEntity is shaped by the database. If you add a column or rename a table, only the entity and the mapping change; the screens keep using Note.
For a tiny app the two classes look identical, and that is fine: the habit is worth having before the app grows.
The Repository: an Interface and an Implementation
- The interface says what the app can do with notes, in app terms (
Note), with no mention of Room. (docs) The function returning a Flow is namedgetNotesStream(). - The mapping happens inside a Flow
map(docs, in the codelab's example): entities go in,Notes come out. - No
withContexthere. (general knowledge) Room's suspend writes run off the main thread themselves, so the repository is already main-safe in the Chapter 3 sense. If you add slow work of your own, switch dispatchers as in Chapter 3.
A Fake for Previews and Tests
Because the ViewModel will depend on the interface, a test can hand it this fake: no database, no emulator. This is the payoff of the interface. It replaces Chapter 3's FakeNotesRepository, which had no interface.
Updating the ViewModel and the State
The ViewModel no longer builds its own repository. It asks for one in its constructor, which is what makes it testable. But the standard viewModel() can no longer create it, because the constructor needs an argument: so the companion object has a small Factory
that reads the NotesApp and gives the ViewModel the app's repository. (general knowledge) That factory shape is the one the official codelab on repositories and manual dependency injection uses. Chapter 9 (Manual Dependency Injection) explains it properly and tidies it.
(general knowledge) The factory code also needs imports for viewModelFactory, initializer and ViewModelProvider; take their exact paths from the IDE's suggestions.
Who May Know What
| Class | May use | Must not use |
|---|---|---|
Composables (NotesScreen) | NotesUiState, Note | Not the ViewModel itself, not the DAO |
NotesViewModel | NotesRepository (the interface), Note | Not NoteDao, not NoteEntity |
DefaultNotesRepository | NoteDao, NoteEntity, Note | Not composables, not the ViewModel |
NoteDao, AppDatabase | NoteEntity | Not Note |
(docs) The point of the last rule in the docs' summary: a state holder (the ViewModel) should never have a data source as a direct dependency. If a change to the database forces a change in a composable, a boundary has leaked.
Testing the ViewModel With the Fake
(docs) The coroutines guidance says to replace Main in tests with Dispatchers.setMain and a test dispatcher, as above. (general knowledge) The test needs the kotlinx-coroutines-test library and a few imports; the details are covered when testing gets its own treatment in Android Development with Compose: Production & Publishing (planned).
getXxxStream naming, Flow instead of LiveData through every layer, and a separate Note model between the entity and the screen.
Try It Yourself
Add Note, the mapping functions, NotesRepository and DefaultNotesRepository; update the ViewModel, the factory, NotesApp and the screen. Run it, add three notes, close the app completely and reopen it. Report whether the notes were still there.
Add FakeNotesRepository and write the ViewModel unit test. Add a second test that adds a real note and checks the list. Report the test dependencies you needed.
Add a delete button to each note, wired all the way from the screen to the DAO. List every file you changed, and say whether any file that should not have changed did.
๐ View solutiongetXxxStream naming; mapping inside a Flow map (a codelab now marked deprecated); a model per layer for complex apps; no data source as a direct dependency of a state holder; Dispatchers.setMain in tests (from the Chapter 3 search).General knowledge, not checked: the interface and fake design; the factory code and its imports (the shape follows the official repository and manual-DI codelab, which was not read); Room suspend writes being main-safe; the unit test and its dependencies; the layer table.
Not verified: every listing and solution (unrun); the exercises (not run by me); the Room 3.0 form of the DAO and entity imports. Nothing was checked on your install.
Sources: Data layer (developer.android.com), Recommendations for Android architecture (developer.android.com), Build an offline-first app (developer.android.com), Building a Data Layer codelab (developer.android.com, deprecated), Add repository and Manual DI codelab (developer.android.com).