Capstone Notes App

Android Development with Compose: Architecture & Data

Course 5 · Chapter 11 · Putting It All Together

You have met every part separately. This chapter asks you to build one small app that uses all of them together: a notes app that stores notes in Room, shows them through a ViewModel, remembers a sort order in DataStore, can fetch sample notes from a server, can export its notes as JSON, and wires its objects together properly. There is very little new teaching here; the point is the joins.

What was checked, and how: read this first
No new docs check for this chapter. Everything it relies on was checked in Chapters 1 to 10 (see each chapter's Not Yet Verified box), and the same labels apply here: the architecture layers and state flow in Chapter 1; ViewModel and StateFlow in Chapter 2; coroutines, stateIn and cancellation in Chapter 3; Room in Chapter 4 (which has the Room 2.x against 3.0 choice); the repository in Chapter 5; serialization in Chapter 6; Retrofit in Chapter 7 (whose converter coordinates are unconfirmed); DataStore in Chapter 8; manual injection in Chapter 9; Hilt in Chapter 10. Added here, general knowledge: the @Update-style targeted query, the five-flow limit of the typed combine and grouping flows into one, the AlertDialog, and the checklist and problems table, which are a summary of what went wrong in earlier chapters, not a docs-checked list. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.

What You Are Building

FeatureUses
Add, edit, delete and list notesRoom, repository, ViewModel, stateless screen (Chapters 1 to 5)
Search as you typeA query held in the ViewModel's state
Newest-first or oldest-firstDataStore setting feeding the state (Chapter 8)
Refresh sample notes from a serverRetrofit, the converter, Room as the source of truth (Chapters 6 and 7)
Export the notes as JSONkotlinx.serialization (Chapter 6)
Objects wired deliberatelyManual container (Chapter 9) or Hilt (Chapter 10): your choice

The Shape of the App

com.example.notes/ ├── NotesApp.kt (Application; @HiltAndroidApp if you chose Hilt) ├── MainActivity.kt ├── di/ (modules, or AppContainer and the factory) ├── data/ │ ├── local/ NoteEntity, NoteDao, AppDatabase (Chapter 4) │ ├── remote/ NotesApi, RemoteNoteDto (Chapters 6 and 7) │ ├── settings/ SettingsRepository + DataStore (Chapter 8) │ ├── Note.kt the model and the mappers (Chapter 5) │ └── NotesRepository.kt interface, default implementation, fake (Chapter 5) └── ui/ └── notes/ ├── NotesUiState.kt (Chapter 1) ├── NotesViewModel.kt (Chapters 2, 3 and 7 to 9) └── NotesScreen.kt route and stateless screen (Chapters 1 and 2)
Room (single source of truth) ──Flow──► NotesRepository ──Flow──► NotesViewModel ──StateFlow──► NotesScreen ▲ ▲ │ │ insertAll (Chapter 7) DataStore Flow │ │ events: add, edit, delete, Retrofit + serialization (sort order) ──────────┘ │ search, refresh, export ▲ ▼ the server ViewModel functions

State flows down the top row; events and the network come in from below. Nothing in the UI knows Room, Retrofit or DataStore exist (Chapter 5's table, who may know what).

Build It in Stages

StageDo this
1. StorageEntity, DAO and database (Chapter 4); the Note model, mappers and repository interface with a fake (Chapter 5). Checkpoint: the DAO test passes.
2. State holderNotesUiState, the ViewModel exposing a StateFlow built from the repository's Flow (Chapters 1 to 3). Checkpoint: the ViewModel test passes against the fake.
3. ScreenRoute and stateless screen with add, delete and a list, plus previews (Chapters 1 and 2). Checkpoint: add a note, rotate, close and reopen: it is still there.
4. Settings, search and editThe DataStore sort switch (Chapter 8), a search box, and editing a note's text. Checkpoint: the sort order survives a restart; search narrows the list as you type.
5. Network and exportRefresh from the server into Room (Chapter 7), and export the notes as JSON (Chapter 6). Checkpoint: aeroplane mode still shows the list, and a failed refresh shows a message.
6. WiringHand-written container and factory (Chapter 9) or Hilt (Chapter 10). Checkpoint: no class builds its own dependencies.

Finish each checkpoint before moving on. If a later stage breaks an earlier checkpoint, that is information about a leaky boundary.

The New Pieces

Three small additions that earlier chapters did not cover. Editing a note, with a targeted query so that other columns are left alone:

// NoteDao: one new query. A targeted update keeps the other columns (such as remoteId) as they were. @Query("UPDATE notes SET text = :text WHERE id = :id") suspend fun updateText(id: Long, text: String) // NotesRepository and DefaultNotesRepository suspend fun updateNoteText(id: Long, text: String) override suspend fun updateNoteText(id: Long, text: String) { noteDao.updateText(id, text) }

(general knowledge) The tempting alternative is @Update with note.toEntity(), but Note has no remoteId, so the mapper would reset it and an imported note would turn into a local one.

The state and a JSON export of the notes:

data class NotesUiState( val notes: List<Note> = emptyList(), val query: String = "", val newestFirst: Boolean = true, val isLoading: Boolean = false, val isRefreshing: Boolean = false, val userMessage: String? = null, val exportText: String? = null )
import kotlinx.serialization.Serializable @Serializable data class NoteExport(val text: String, val createdAt: Long) fun exportNotesAsJson(notes: List<Note>): String = json.encodeToString(notes.map { NoteExport(it.text, it.createdAt) })
// In NotesScreen: the export result in a dialog state.exportText?.let { text -> AlertDialog( onDismissRequest = onExportShown, confirmButton = { TextButton(onClick = onExportShown) { Text("Close") } }, text = { Text(text) } ) }

Here is the whole ViewModel, so you can see the earlier chapters joined. Notice the Transient class: the typed combine takes five flows (general knowledge), so the short-lived bits (a message and the export text) are grouped into one flow.

@HiltViewModel // or no annotation, if you chose manual DI class NotesViewModel @Inject constructor( private val repository: NotesRepository, private val settings: SettingsRepository ) : ViewModel() { // Five flows is the limit of the typed combine: group the small, transient bits into one private data class Transient(val message: String? = null, val exportText: String? = null) private val transient = MutableStateFlow(Transient()) private val query = MutableStateFlow("") private val isRefreshing = MutableStateFlow(false) val uiState: StateFlow<NotesUiState> = combine( repository.getNotesStream(), settings.newestFirst, query, transient, isRefreshing ) { notes, newestFirst, q, t, refreshing -> val shown = notes.filter { it.text.contains(q, ignoreCase = true) } NotesUiState( notes = if (newestFirst) shown.sortedByDescending { it.createdAt } else shown.sortedBy { it.createdAt }, query = q, newestFirst = newestFirst, isRefreshing = refreshing, userMessage = t.message, exportText = t.exportText ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = NotesUiState(isLoading = true) ) fun onQueryChange(value: String) { query.value = value } fun setNewestFirst(value: Boolean) { viewModelScope.launch { settings.setNewestFirst(value) } } fun addNote(text: String) { if (text.isBlank()) { showMessage("A note cannot be empty"); return } viewModelScope.launch { repository.addNote(text) } } fun updateNote(id: Long, text: String) { if (text.isBlank()) { showMessage("A note cannot be empty"); return } viewModelScope.launch { repository.updateNoteText(id, text) } } fun deleteNote(note: Note) { viewModelScope.launch { repository.deleteNote(note) } } fun refresh() { viewModelScope.launch { isRefreshing.value = true val result = repository.refresh() isRefreshing.value = false when (result) { RefreshResult.Success -> Unit RefreshResult.NoConnection -> showMessage("No connection") is RefreshResult.ServerError -> showMessage("Server error (${result.code})") RefreshResult.BadReply -> showMessage("Unexpected reply from the server") } } } fun exportNotes() { viewModelScope.launch { val notes = repository.getNotesStream().first() transient.update { it.copy(exportText = exportNotesAsJson(notes)) } } } fun exportShown() = transient.update { it.copy(exportText = null) } fun messageShown() = transient.update { it.copy(message = null) } private fun showMessage(text: String) = transient.update { it.copy(message = text) } }

Three Kinds of Test

// 1. DAO (androidTest, in-memory Room, Chapter 4) @Test fun insertedNoteIsObserved() = runTest { /* as in Chapter 4 */ } // 2. ViewModel (JVM, fakes, Chapters 5 and 9) @Test fun emptyNoteShowsMessage() = runTest { val viewModel = NotesViewModel(FakeNotesRepository(), FakeSettingsRepository()) viewModel.addNote(" ") assertEquals("A note cannot be empty", viewModel.uiState.value.userMessage) } // 3. Serialization (JVM, Chapter 6) @Test fun exportContainsTheText() { val text = exportNotesAsJson(listOf(Note(1, "Hi", 5L))) assertTrue(text.contains("Hi")) }

Acceptance Checklist

Your capstone is done when every line is true:

  • ☐ The UI never imports a DAO, an entity, Retrofit or DataStore.
  • ☐ Every screen state can be previewed without running the app.
  • ☐ The list survives rotation, closing the app and aeroplane mode.
  • ☐ A failed refresh shows a message and does not clear the list.
  • ☐ The sort order survives a restart.
  • ☐ One database, one Retrofit instance, one DataStore for the whole app.
  • ☐ No loading starts in a ViewModel's init.
  • ☐ Cancellation is never swallowed (CancellationException is rethrown if you catch broadly).
  • ☐ The ViewModel can be built in a test with fakes and no Android.
  • ☐ All versions are current and the build is clean.

When Something Goes Wrong

SymptomLikely cause
Build fails in a generated Room or Hilt classWrong or mismatched plugin, KSP or library versions (Chapters 4 and 10); a typo in an annotation or query.
App crashes on first run after changing the entityThe database version was not raised or there is no migration; uninstall while developing (Chapter 7).
List is empty until the first refreshExpected: the table starts empty; show a helpful empty state, or refresh when the table is empty (Chapter 7, Exercise 3).
Fetch works but notes overwrite each otherServer ids stored as local ids; use a separate remoteId with a unique index (Chapter 7).
State never updates after a changeThe upstream flow is not being collected: with WhileSubscribed nothing runs without a collector (Chapter 3).
Hilt reports a missing bindingAn interface without a @Binds, or a class without an @Inject constructor (Chapter 10).
Compared with the Classic UI course
Android Development: Architecture & Data has no capstone chapter. This one is new, and it is the Compose-first course's answer to "how do these ten pieces fit in one app?". The larger worked project that applies all of this is Personal Catalogue: Android (Kotlin & Compose).

Try It Yourself

Exercise 1

Build stages 1 to 3: storage, the state holder and the screen. Show the checkpoint results: the DAO test and the ViewModel test passing, and a note that survives rotation and a restart.

📄 View solution
Exercise 2

Build stages 4 and 5: the sort setting, search, editing, refresh from the server and the JSON export. Report which stage took longest, and which earlier chapter you had to reread.

📄 View solution
Exercise 3

Build stage 6 your chosen way, then walk the acceptance checklist and write down any line that is not yet true. Finish with a short review: if the server went away for good, what would you have to change, and what could stay exactly as it is?

📄 View solution
Not Yet Verified
Checked in the docs: nothing new in this chapter. All docs checks are in Chapters 1 to 10, with the gaps and unresolved points noted there (the Room 2.x and 3.0 split, the unconfirmed Retrofit converter coordinates, the Hilt compiler artifact name, the collectAsStateWithLifecycle version note).
General knowledge, not checked: the targeted update query; the five-flow limit of the typed combine; the AlertDialog code; the file layout; the checklist and the problems table.
Not verified: the complete app has never been built or run, so the pieces from different chapters may need small fixes to compile together; every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install.
Sources: the sources listed in the Not Yet Verified boxes of Android Development with Compose: Architecture & Data 1 to 10.
Course Complete
You can now organise an app into layers, hold its state in a ViewModel, store and fetch its data, remember its settings and wire it together. Next in the Android track: Android Development with Compose: Production & Publishing (android6, not yet written), and Personal Catalogue: Android (Kotlin & Compose), a larger project that applies all of this.