Notes app with Compose and Room
What you will build
The finished app lets a user create, read, edit, search, and delete notes stored in a local Room database. The UI is built entirely with Jetpack Compose and Material 3. A ViewModel exposes a single StateFlow of UI state; the Compose layer collects it with collectAsStateWithLifecycle and renders a LazyColumn of notes. Deleting a note shows a snackbar with an "Undo" action that re-inserts the row. Navigation between the list and detail screens uses type-safe Navigation Compose routes. The app draws edge-to-edge and supports light and dark themes. A small set of JUnit tests drives the ViewModel with a fake repository. This project proves you can wire Room, Compose, coroutines, and a unidirectional data flow into one working app without a heavy framework. It is small enough that a reviewer can read it end to end in one sitting.
Skills you practise
- Jetpack Compose with Material 3
- Room with Flow-based queries and KSP
- ViewModel with StateFlow UI state
- Kotlin coroutines and Flow operators
- Type-safe Navigation Compose
- One-off events (the undo snackbar) modelled as UI state
- Unit testing with a fake repository and a test dispatcher
Architecture
The app is a single module with three layers. The data layer holds a Room database, a Note entity, and a NoteDao that exposes Flow<List<Note>> for reads and suspend functions for writes. A NotesRepository interface wraps the DAO; a concrete RoomNotesRepository implements it. Room runs suspend DAO calls and Flow queries on its own background executor, so they are already main-safe: the repository does not need withContext(Dispatchers.IO). If you later add other blocking work, inject the dispatcher through the constructor instead of hard-coding it. There is no separate domain layer: the repository interface is the contract, and there are no use-case classes. The presentation layer has a NotesViewModel that combines the search query, the Room Flow (switched with flatMapLatest when the query changes), and a "recently deleted note" field into one NoteUiState. The undo snackbar is driven by that field: the UI shows the snackbar when it is non-null, then tells the ViewModel it is done, and the ViewModel clears it. The Compose UI collects uiState with collectAsStateWithLifecycle. Navigation uses @Serializable route classes with composable<Route>. Data flows one direction: user input -> ViewModel -> repository -> Room -> Flow back to the UI. No shared mutable state lives outside the ViewModel and the database.
| Module or layer | Responsibility |
|---|---|
| Data layer | Room database, Note entity, NoteDao with Flow queries, NotesRepository interface and RoomNotesRepository implementation. |
| Presentation layer | NotesViewModel and NoteDetailViewModel with StateFlow UI state, search, delete, undo, and edit logic. |
| UI layer | Compose screens (NoteListScreen, NoteDetailScreen), NavHost with type-safe routes, Scaffold with SnackbarHost, Material 3 theme. |
| Test layer | FakeNotesRepository, a MainDispatcherRule, and JUnit tests that exercise the ViewModel on the JVM. |
Milestones
1. Project scaffold and Room database
Create a single-module Compose project with a Room database that stores and reads notes.
- Create a new project in Android Studio with the Empty Activity (Compose) template, Kotlin, minimum SDK 24.
- Add the KSP Gradle plugin, the Room runtime library, and the Room compiler through
ksp(...). Check that the Compose BOM,lifecycle-viewmodel-compose, andlifecycle-runtime-composeare inbuild.gradle.kts(the template adds some of them). - Define a
Noteentity with an auto-generatedid: Long,title,body, and acreatedAttimestamp. - Write a
NoteDaowith a@Querythat returnsFlow<List<Note>>ordered bycreatedAt, plussuspendinsert,update, anddeletefunctions. - Create an abstract
NotesDatabaseclass extendingRoomDatabase, and build one instance in yourApplicationsubclass (register it in the manifest). Keep aRoomNotesRepositorythere too, so ViewModels can reach it.
Done when: The app compiles, and a note inserted from lifecycleScope.launch in onCreate shows up in Logcat when you collect the DAO's Flow.
Lessons: android studio project structure, gradle basics and build variants, room entities daos queries
2. ViewModel, StateFlow, and repository
Put state and logic in a ViewModel that exposes a single StateFlow<NoteUiState>.
- Define a
NoteUiStatedata class holdingnotes,query, and anisLoadingflag. - Create a
NotesRepositoryinterface withobserveNotes(query),insertNote, anddeleteNote, and makeRoomNotesRepositorydelegate to the DAO. - In
NotesViewModel, keep the query in a privateMutableStateFlowand useflatMapLatestto switch to a new Room query when it changes.flatMapLatestneeds@OptIn(ExperimentalCoroutinesApi::class). - Turn the result into
uiStatewithstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NoteUiState()). - Construct the ViewModel with a
viewModelFactory { initializer { ... } }that reads the repository from yourApplicationviathis[APPLICATION_KEY].
Done when: uiState is the only public state, every MutableStateFlow is private, and nothing in Compose calls the repository directly.
Lessons: viewmodel and ui state, repository pattern, flow operators
3. Compose UI for the note list
Render a scrollable list of notes with a Material 3 theme and a create-note button.
- Use the template's
Theme.kt, which has light and dark color schemes (and dynamic color on Android 12+). - Build a stateless
NoteListScreenthat takes aList<Note>and callbacks, and renders aLazyColumnwithkey = { it.id }. - Each item shows the title and a body preview with
maxLines = 2andoverflow = TextOverflow.Ellipsis. - Add a
FloatingActionButtonthat opens anAlertDialogwith twoTextFields to create a note. - In a
NoteListRoutecomposable, get the ViewModel withviewModel(factory = ...), collectuiStatewithcollectAsStateWithLifecycle(), and pass the values down.
Done when: The list shows notes from Room, a new note appears right after you save it, and the UI follows the system dark mode.
Lessons: composables and modifiers, lists with lazycolumn, collecting flows safely in the ui
4. Search and delete with undo snackbar
Add live search and a delete-with-undo snackbar, with the undo event held in UI state.
- Add a search
TextFieldabove the list; on each change callviewModel.onQueryChange(text). The field showsuiState.query. - Change the DAO query to filter with
title LIKE '%' || :query || '%'. SQLite'sLIKEignores case for ASCII letters. - Add a nullable
deletedNote: Note?toNoteUiState. On delete, the ViewModel callsrepo.deleteNote(note)and then setsdeletedNote. - Put a
SnackbarHost(snackbarHostState)in theScaffold. In aLaunchedEffect(uiState.deletedNote), callsnackbarHostState.showSnackbar(message = "Note deleted", actionLabel = "Undo", duration = SnackbarDuration.Short). In Material 3 a snackbar with an action defaults toIndefinite, so set the duration yourself. - If the result is
SnackbarResult.ActionPerformed, callviewModel.undoDelete(), which re-inserts the note (sameid) and clearsdeletedNote. Otherwise callviewModel.undoMessageShown()to clear it. - Add a swipe-to-dismiss or a delete icon on each item to trigger the delete.
Done when: Typing filters the list as you type; deleting shows a snackbar; tapping Undo restores the note; rotating the device while the snackbar is showing does not lose it or show it twice after it is handled.
Lessons: one off events done right, side effects launchedeffect and friends, stateflow and sharedflow
5. Navigation, edge-to-edge, and the detail screen
Add type-safe navigation to an edit screen and draw the app edge-to-edge.
- Add the Kotlin serialization plugin and
navigation-compose(2.8.0 or newer). Define@Serializable object NoteListand@Serializable data class NoteDetail(val noteId: Long). - Set up a
NavHost(navController, startDestination = NoteList)withcomposable<NoteList>andcomposable<NoteDetail>. Navigate withnavController.navigate(NoteDetail(note.id))and read the id withbackStackEntry.toRoute<NoteDetail>(). - Add
observeNote(id)andupdateNote(note)to the DAO and repository. Build aNoteDetailScreenwithTextFields for title and body that saves through aNoteDetailViewModelon "Done", then pops back. - Call
enableEdgeToEdge()beforesetContentinMainActivity. Apply theinnerPaddingthatScaffoldpasses to its content, so the list and FAB stay clear of the status and navigation bars. - Check both screens in light and dark theme, with gesture and three-button navigation.
Done when: Tapping a note opens the detail screen with its text; saving updates the list; Back returns to the list; content draws behind the system bars but no text is hidden by them.
Lessons: navigation in compose, state hoisting, material 3 theming
6. Unit tests for the ViewModel
Write JVM unit tests that check search, delete, and undo without an emulator.
- Create a
FakeNotesRepositorythat keeps notes in aMutableStateFlow<List<Note>>and filters them inobserveNotes(query). - Add a
MainDispatcherRule(a JUnitTestWatcher) that callsDispatchers.setMain(StandardTestDispatcher())before each test andDispatchers.resetMain()after. - Because
uiStateusesstateIn(WhileSubscribed), start a collector first:backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.uiState.collect() }. - Test that
onQueryChange("milk")leaves only matching notes inuiState.value.notesafteradvanceUntilIdle(). - Test that
delete(note)removes the note and setsdeletedNote, thatundoDelete()brings it back and clearsdeletedNote, and thatundoMessageShown()clears it without re-inserting.
Done when: All tests pass with ./gradlew testDebugUnitTest, with no emulator or Robolectric.
Lessons: viewmodel tests, testing coroutines and flows, fakes vs mocks
Key code
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val title: String,
val body: String,
val createdAt: Long = System.currentTimeMillis(),
)
interface NotesRepository {
fun observeNotes(query: String): Flow<List<Note>>
suspend fun insertNote(note: Note)
suspend fun deleteNote(note: Note)
}
data class NoteUiState(
val notes: List<Note> = emptyList(),
val query: String = "",
val isLoading: Boolean = true,
val deletedNote: Note? = null, // drives the undo snackbar
)
@OptIn(ExperimentalCoroutinesApi::class)
class NotesViewModel(private val repo: NotesRepository) : ViewModel() {
private val query = MutableStateFlow("")
private val deletedNote = MutableStateFlow<Note?>(null)
val uiState: StateFlow<NoteUiState> = combine(
query,
query.flatMapLatest { q -> repo.observeNotes(q) },
deletedNote,
) { q, notes, deleted ->
NoteUiState(notes = notes, query = q, isLoading = false, deletedNote = deleted)
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NoteUiState())
fun onQueryChange(text: String) { query.value = text }
fun delete(note: Note) {
viewModelScope.launch {
repo.deleteNote(note) // Room suspend calls are main-safe
deletedNote.value = note
}
}
fun undoDelete() {
val note = deletedNote.value ?: return
deletedNote.value = null
viewModelScope.launch { repo.insertNote(note) } // same id, so it comes back in place
}
fun undoMessageShown() { deletedNote.value = null }
}The screen side shows the snackbar from state and reports back:
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
uiState.deletedNote?.let { deleted ->
LaunchedEffect(deleted) {
val result = snackbarHostState.showSnackbar(
message = "Note deleted",
actionLabel = "Undo",
duration = SnackbarDuration.Short,
)
if (result == SnackbarResult.ActionPerformed) viewModel.undoDelete()
else viewModel.undoMessageShown()
}
}
Scaffold(snackbarHost = { SnackbarHost(snackbarHostState) }) { innerPadding ->
NoteListScreen(
notes = uiState.notes,
onDelete = viewModel::delete,
modifier = Modifier.padding(innerPadding),
)
}flatMapLatestcancels the collection of the previous Room query when the search text changes, so only the latest query is observed and old results cannot overwrite new ones.- The undo event lives in
NoteUiState, not in aChannel. If the device rotates while the snackbar is visible, the effect is cancelled and the snackbar is removed, butdeletedNoteis still set in the ViewModel, so the new composition shows it again. It is cleared only after the user acts or the snackbar times out, so it is handled exactly once. SharingStarted.WhileSubscribed(5_000)stops the Room query 5 seconds after the last collector goes away. The 5-second timeout keeps it running through a rotation. PlainWhileSubscribed()has a timeout of 0 and would restart the query on every configuration change.- If the user deletes a second note while the first snackbar is showing,
deletedNoteis replaced and the effect restarts for the newer note. That is fine for this app; a queue of deleted notes is a stretch goal.
Pitfalls
- Collecting the state with collectAsState or a raw collect inside LaunchedEffect. Both stop when the composable leaves the composition, but keep collecting while the app is in the background, because the composition is not destroyed when the activity stops. Fix: use
collectAsStateWithLifecycle()fromlifecycle-runtime-compose, which collects only while the lifecycle is at leastSTARTED. - Exposing MutableStateFlow publicly from the ViewModel. Any caller can change state, which breaks unidirectional data flow and makes bugs hard to trace. Fix: keep
MutableStateFlowprivate and expose a read-onlyStateFlow(fromstateInorasStateFlow()). - Using a Channel or SharedFlow for the undo event. A
SharedFlow(replay = 0)drops the event if nobody is collecting, and aChannelcan lose it if the collector is cancelled right after receiving it, for example on rotation. Fix: keep it as a nullable field in the UI state and clear it when the UI has handled it. - Forgetting the duration on a snackbar with an action. In Material 3,
showSnackbarwith anactionLabeldefaults toSnackbarDuration.Indefinite, so the snackbar never goes away by itself. Fix: passduration = SnackbarDuration.ShortorLong. - Room LIKE with unescaped user input. A
%or_in the search text acts as a wildcard and matches the wrong notes. Fix: addESCAPE '\'to the query and escape\,%, and_in the text before passing it in. The bound parameter already protects you from SQL injection; this is only about wildcards. - Ignoring the Scaffold's innerPadding after enableEdgeToEdge(). The list scrolls under the status bar and the last item hides behind the navigation bar. Fix: apply the
innerPaddingthat the Material 3Scaffoldpasses to its content (orcontentPaddingon theLazyColumn). Apps that target Android 15 or higher are edge-to-edge by default, so you need this anyway.
Code review finding
- The first version sent the deleted note through a
Channel<Note>exposed withreceiveAsFlow(), collected in aLaunchedEffect(Unit)that calledshowSnackbar. - If the user rotated the device while the snackbar was visible, the effect was cancelled, the snackbar disappeared, and the note had already been taken out of the channel. The new composition had nothing to show.
- The user lost the chance to undo a delete, which is the whole point of the snackbar.
- Replace the
Channelwith adeletedNote: Note?field inNoteUiState, owned by the ViewModel, which survives rotation. - Show the snackbar in a
LaunchedEffectkeyed on that note. WhenshowSnackbarreturns, callundoDelete()orundoMessageShown(), and both clear the field. - Add unit tests for both paths: the field is set after
delete, and cleared after either call.
Stretch goals
- Add a
Roommigration from version 1 to version 2 (add acolorcolumn) and test it withMigrationTestHelper. - Replace manual construction with
Hiltfor dependency injection. - Add a Compose UI test that checks the snackbar appears after a delete and that tapping Undo brings the note back.
- Persist the last search query in
DataStoreso it survives an app restart. - Search the body as well as the title, or use a Room FTS table for faster full-text search.
- Add
Paging 3to the list if you load thousands of notes.
Done checklist
- All
MutableStateFlowinstances areprivate; only read-onlyStateFlowis exposed from the ViewModels. uiStateis collected withcollectAsStateWithLifecycle().- The
LazyColumnuses a stablekey(the noteid) for each item. - Navigation uses
@Serializableroutes,composable<Route>, andtoRoute(); there are no string routes. - The undo snackbar is driven by UI state and is handled exactly once per delete, even across rotation.
- Edge-to-edge is enabled and the
Scaffold'sinnerPaddingis applied. - Unit tests cover search, delete, undo, and dismiss; all pass with
./gradlew testDebugUnitTest. - No
TODO(),println, or placeholder code remains in the source tree.
Talking about it in an interview
- Explain why you chose
flatMapLatestoverflatMapConcatfor search. A RoomFlownever completes, soflatMapConcatwould stay on the first query forever;flatMapLatestcancels the old query as soon as the text changes. - Explain why the undo event is UI state, not a
ChannelorSharedFlow. State survives rotation in the ViewModel, the UI acknowledges it explicitly, and it is easy to test. AChannelcan lose an event that a cancelled collector already received, and aSharedFlowwith no replay drops events when nobody collects. - Describe how
collectAsStateWithLifecycleties collection to the lifecycle, so the Room query stops in the background, and howWhileSubscribed(5_000)keeps it alive across a rotation. - Explain why the repository does not switch dispatchers: Room
suspendandFlowqueries already run off the main thread. Say that you would inject a dispatcher for any other blocking work so tests can replace it. - Mention what you would change for production: Hilt for DI, Room migrations with
MigrationTestHelper, Compose UI tests, and a queue for several quick deletes.