Notes app with Compose and Room

Build a notes app with Jetpack Compose, Room, and a ViewModel with StateFlow: search, edit, and delete notes with an undo snackbar and type-safe navigation. About 16 hours.

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 layerResponsibility
Data layerRoom database, Note entity, NoteDao with Flow queries, NotesRepository interface and RoomNotesRepository implementation.
Presentation layerNotesViewModel and NoteDetailViewModel with StateFlow UI state, search, delete, undo, and edit logic.
UI layerCompose screens (NoteListScreen, NoteDetailScreen), NavHost with type-safe routes, Scaffold with SnackbarHost, Material 3 theme.
Test layerFakeNotesRepository, 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.

  1. Create a new project in Android Studio with the Empty Activity (Compose) template, Kotlin, minimum SDK 24.
  2. Add the KSP Gradle plugin, the Room runtime library, and the Room compiler through ksp(...). Check that the Compose BOM, lifecycle-viewmodel-compose, and lifecycle-runtime-compose are in build.gradle.kts (the template adds some of them).
  3. Define a Note entity with an auto-generated id: Long, title, body, and a createdAt timestamp.
  4. Write a NoteDao with a @Query that returns Flow<List<Note>> ordered by createdAt, plus suspend insert, update, and delete functions.
  5. Create an abstract NotesDatabase class extending RoomDatabase, and build one instance in your Application subclass (register it in the manifest). Keep a RoomNotesRepository there 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>.

  1. Define a NoteUiState data class holding notes, query, and an isLoading flag.
  2. Create a NotesRepository interface with observeNotes(query), insertNote, and deleteNote, and make RoomNotesRepository delegate to the DAO.
  3. In NotesViewModel, keep the query in a private MutableStateFlow and use flatMapLatest to switch to a new Room query when it changes. flatMapLatest needs @OptIn(ExperimentalCoroutinesApi::class).
  4. Turn the result into uiState with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NoteUiState()).
  5. Construct the ViewModel with a viewModelFactory { initializer { ... } } that reads the repository from your Application via this[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.

  1. Use the template's Theme.kt, which has light and dark color schemes (and dynamic color on Android 12+).
  2. Build a stateless NoteListScreen that takes a List<Note> and callbacks, and renders a LazyColumn with key = { it.id }.
  3. Each item shows the title and a body preview with maxLines = 2 and overflow = TextOverflow.Ellipsis.
  4. Add a FloatingActionButton that opens an AlertDialog with two TextFields to create a note.
  5. In a NoteListRoute composable, get the ViewModel with viewModel(factory = ...), collect uiState with collectAsStateWithLifecycle(), 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.

  1. Add a search TextField above the list; on each change call viewModel.onQueryChange(text). The field shows uiState.query.
  2. Change the DAO query to filter with title LIKE '%' || :query || '%'. SQLite's LIKE ignores case for ASCII letters.
  3. Add a nullable deletedNote: Note? to NoteUiState. On delete, the ViewModel calls repo.deleteNote(note) and then sets deletedNote.
  4. Put a SnackbarHost(snackbarHostState) in the Scaffold. In a LaunchedEffect(uiState.deletedNote), call snackbarHostState.showSnackbar(message = "Note deleted", actionLabel = "Undo", duration = SnackbarDuration.Short). In Material 3 a snackbar with an action defaults to Indefinite, so set the duration yourself.
  5. If the result is SnackbarResult.ActionPerformed, call viewModel.undoDelete(), which re-inserts the note (same id) and clears deletedNote. Otherwise call viewModel.undoMessageShown() to clear it.
  6. 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.

  1. Add the Kotlin serialization plugin and navigation-compose (2.8.0 or newer). Define @Serializable object NoteList and @Serializable data class NoteDetail(val noteId: Long).
  2. Set up a NavHost(navController, startDestination = NoteList) with composable<NoteList> and composable<NoteDetail>. Navigate with navController.navigate(NoteDetail(note.id)) and read the id with backStackEntry.toRoute<NoteDetail>().
  3. Add observeNote(id) and updateNote(note) to the DAO and repository. Build a NoteDetailScreen with TextFields for title and body that saves through a NoteDetailViewModel on "Done", then pops back.
  4. Call enableEdgeToEdge() before setContent in MainActivity. Apply the innerPadding that Scaffold passes to its content, so the list and FAB stay clear of the status and navigation bars.
  5. 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.

  1. Create a FakeNotesRepository that keeps notes in a MutableStateFlow<List<Note>> and filters them in observeNotes(query).
  2. Add a MainDispatcherRule (a JUnit TestWatcher) that calls Dispatchers.setMain(StandardTestDispatcher()) before each test and Dispatchers.resetMain() after.
  3. Because uiState uses stateIn(WhileSubscribed), start a collector first: backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) { viewModel.uiState.collect() }.
  4. Test that onQueryChange("milk") leaves only matching notes in uiState.value.notes after advanceUntilIdle().
  5. Test that delete(note) removes the note and sets deletedNote, that undoDelete() brings it back and clears deletedNote, and that undoMessageShown() 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),
    )
}
  • flatMapLatest cancels 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 a Channel. If the device rotates while the snackbar is visible, the effect is cancelled and the snackbar is removed, but deletedNote is 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. Plain WhileSubscribed() 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, deletedNote is 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() from lifecycle-runtime-compose, which collects only while the lifecycle is at least STARTED.
  • Exposing MutableStateFlow publicly from the ViewModel. Any caller can change state, which breaks unidirectional data flow and makes bugs hard to trace. Fix: keep MutableStateFlow private and expose a read-only StateFlow (from stateIn or asStateFlow()).
  • Using a Channel or SharedFlow for the undo event. A SharedFlow(replay = 0) drops the event if nobody is collecting, and a Channel can 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, showSnackbar with an actionLabel defaults to SnackbarDuration.Indefinite, so the snackbar never goes away by itself. Fix: pass duration = SnackbarDuration.Short or Long.
  • Room LIKE with unescaped user input. A % or _ in the search text acts as a wildcard and matches the wrong notes. Fix: add ESCAPE '\' 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 innerPadding that the Material 3 Scaffold passes to its content (or contentPadding on the LazyColumn). Apps that target Android 15 or higher are edge-to-edge by default, so you need this anyway.

Code review finding

Undo snackbar is sometimes lost after rotation
  • The first version sent the deleted note through a Channel<Note> exposed with receiveAsFlow(), collected in a LaunchedEffect(Unit) that called showSnackbar.
  • 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.
The fix
  • Replace the Channel with a deletedNote: Note? field in NoteUiState, owned by the ViewModel, which survives rotation.
  • Show the snackbar in a LaunchedEffect keyed on that note. When showSnackbar returns, call undoDelete() or undoMessageShown(), 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 Room migration from version 1 to version 2 (add a color column) and test it with MigrationTestHelper.
  • Replace manual construction with Hilt for 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 DataStore so 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 3 to the list if you load thousands of notes.

Done checklist

  • All MutableStateFlow instances are private; only read-only StateFlow is exposed from the ViewModels.
  • uiState is collected with collectAsStateWithLifecycle().
  • The LazyColumn uses a stable key (the note id) for each item.
  • Navigation uses @Serializable routes, composable<Route>, and toRoute(); 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's innerPadding is 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 flatMapLatest over flatMapConcat for search. A Room Flow never completes, so flatMapConcat would stay on the first query forever; flatMapLatest cancels the old query as soon as the text changes.
  • Explain why the undo event is UI state, not a Channel or SharedFlow. State survives rotation in the ViewModel, the UI acknowledges it explicitly, and it is easy to test. A Channel can lose an event that a cancelled collector already received, and a SharedFlow with no replay drops events when nobody collects.
  • Describe how collectAsStateWithLifecycle ties collection to the lifecycle, so the Room query stops in the background, and how WhileSubscribed(5_000) keeps it alive across a rotation.
  • Explain why the repository does not switch dispatchers: Room suspend and Flow queries 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.