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.

What was checked, and how: read this first
Checked in the docs (one web search, summaries only): repositories are recommended even when they wrap one data source; the UI is driven from data models that respect the single source of truth; a local database is the recommended source of truth when offline-first support matters; a class exposing a 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

// The model the UI and the ViewModel use: plain data, no Room annotations data class Note( val id: Long, val text: String, val createdAt: Long ) // Mapping between the storage class (Chapter 4) and the model fun NoteEntity.toModel() = Note(id = id, text = text, createdAt = createdAt) fun Note.toEntity() = NoteEntity(id = id, text = text, createdAt = createdAt)

(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

import kotlinx.coroutines.flow.Flow interface NotesRepository { // Naming convention for a function that returns a Flow: getXxxStream fun getNotesStream(): Flow<List<Note>> suspend fun addNote(text: String) suspend fun deleteNote(note: Note) }
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map class DefaultNotesRepository( private val noteDao: NoteDao ) : NotesRepository { override fun getNotesStream(): Flow<List<Note>> = noteDao.observeNotes().map { entities -> entities.map { it.toModel() } } override suspend fun addNote(text: String) { noteDao.insert(NoteEntity(text = text)) } override suspend fun deleteNote(note: Note) { noteDao.delete(note.toEntity()) } }
  • 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 named getNotesStream().
  • The mapping happens inside a Flow map (docs, in the codelab's example): entities go in, Notes come out.
  • No withContext here. (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

import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update // For previews and tests: same interface, no database class FakeNotesRepository : NotesRepository { private val notes = MutableStateFlow(listOf(Note(1, "Buy milk", 0L))) override fun getNotesStream(): Flow<List<Note>> = notes override suspend fun addNote(text: String) { notes.update { it + Note(it.size + 1L, text, 0L) } } override suspend fun deleteNote(note: Note) { notes.update { it - note } } }

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

data class NotesUiState( val notes: List<Note> = emptyList(), // was List<String> val isLoading: Boolean = false, val userMessage: String? = null )
class NotesViewModel( private val repository: NotesRepository // the interface, not the Room class ) : ViewModel() { private val message = MutableStateFlow<String?>(null) val uiState: StateFlow<NotesUiState> = combine(repository.getNotesStream(), message) { notes, userMessage -> NotesUiState(notes = notes, isLoading = false, userMessage = userMessage) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = NotesUiState(isLoading = true) ) fun addNote(text: String) { if (text.isBlank()) { message.value = "A note cannot be empty" return } viewModelScope.launch { try { repository.addNote(text) } catch (e: CancellationException) { throw e } catch (e: Exception) { message.value = "Could not save the note" } } } fun deleteNote(note: Note) { viewModelScope.launch { repository.deleteNote(note) } } fun messageShown() { message.value = null } companion object { // A small hand-written factory: Chapter 9 explains and tidies this val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val app = this[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY] as NotesApp NotesViewModel(app.notesRepository) } } } }

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.

class NotesApp : Application() { val database: AppDatabase by lazy { Room.databaseBuilder(applicationContext, AppDatabase::class.java, "notes.db").build() } // The one place that builds the repository val notesRepository: NotesRepository by lazy { DefaultNotesRepository(database.noteDao()) } }
@Composable fun NotesRoute(viewModel: NotesViewModel = viewModel(factory = NotesViewModel.Factory)) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() NotesScreen( state = uiState, onAddNote = viewModel::addNote, onDeleteNote = viewModel::deleteNote, onMessageShown = viewModel::messageShown ) } // In the list, the screen now shows note.text: items(state.notes) { note -> Text(note.text) }

(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

ClassMay useMust not use
Composables (NotesScreen)NotesUiState, NoteNot the ViewModel itself, not the DAO
NotesViewModelNotesRepository (the interface), NoteNot NoteDao, not NoteEntity
DefaultNotesRepositoryNoteDao, NoteEntity, NoteNot composables, not the ViewModel
NoteDao, AppDatabaseNoteEntityNot 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

// app/src/test/.../NotesViewModelTest.kt (a plain JVM test: no emulator) @OptIn(ExperimentalCoroutinesApi::class) class NotesViewModelTest { @Before fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) @After fun tearDown() = Dispatchers.resetMain() @Test fun emptyNoteShowsMessage() = runTest { val viewModel = NotesViewModel(FakeNotesRepository()) viewModel.addNote(" ") assertEquals("A note cannot be empty", viewModel.uiState.value.userMessage) } }

(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).

Compared with the Classic UI course
Android Development: Architecture & Data 8 teaches the repository pattern, clean architecture basics and separating concerns, mostly with LiveData. The structure is the same. What is new here is the getXxxStream naming, Flow instead of LiveData through every layer, and a separate Note model between the entity and the screen.

Try It Yourself

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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.

๐Ÿ“„ View solution
Exercise 3

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 solution
Not Yet Verified
Checked in the docs (one web search, summaries only): repositories even for one data source; the single source of truth; a local database as the recommended source of truth for offline-first; getXxxStream 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).
Coming up
Chapter 6 is Kotlin Serialization and JSON: what JSON is, how to turn it into Kotlin classes, and how to cope with bad data, ready for the network call in Chapter 7.