Shopping app with cart and checkout

Build a shopping app with Jetpack Compose, Paging 3, Room, Hilt, and Navigation Compose that persists a cart and validates checkout. About 34 hours.

What you will build

The finished app shows a paginated product list, a detail screen, a cart that survives process death, and a checkout form with field-level validation. Orders are mocked; no real payment runs.

This project proves you can wire Jetpack Compose, Paging 3, Room, Hilt, and type-safe Navigation Compose into one coherent app. It shows you understand Room as a single source of truth, SavedStateHandle for form recovery, and one-off events such as navigating after a successful order. An employer sees a developer who can build a multi-screen feature end to end, handle state correctly, and write tests that catch real bugs.

Skills you practise

  • Paging 3 with collectAsLazyPagingItems() in Compose
  • Room persistence with Flow-based queries as the cart's source of truth
  • Atomic quantity updates in a DAO @Transaction
  • Type-safe Navigation Compose with @Serializable routes and toRoute()
  • SavedStateHandle for form state that survives process death
  • One-off events modelled as UI state the screen acknowledges
  • Hilt dependency injection across layers
  • ViewModel tests with runTest and Compose UI tests

Architecture

The app uses unidirectional data flow. Each screen owns a ViewModel that exposes UI state. Compose collects that state and renders it. User actions call functions on the ViewModel, which updates state or calls a repository.

Products: Retrofit calls a REST API. A PagingSource wraps the paged endpoint. The list ViewModel exposes a Flow<PagingData<Product>> with cachedIn(viewModelScope), and the screen collects it with collectAsLazyPagingItems() to feed a LazyColumn.

Cart: Room stores CartItem rows and is the single source of truth. The DAO's Flow<List<CartItem>> is mapped to UI state in CartViewModel with stateIn. Quantity changes are written to Room as relative, atomic updates; the Flow re-emits and the UI follows. There is no in-memory copy that can drift from the database.

Checkout: The fields that are safe to keep (name, email, address) live in SavedStateHandle, so they survive process death. Validation runs on each change. On submit, a mock order API is called. Success sets placedOrderId in the UI state; the screen navigates to the confirmation screen and then tells the ViewModel the event was handled.

DI: Hilt provides Retrofit, the Room database, DAOs, and repository bindings; ViewModels are annotated @HiltViewModel and obtained with hiltViewModel(). Navigation uses one NavHost whose destinations are @Serializable route objects and classes.

Module or layerResponsibility
UI (Compose screens + ViewModels)Each screen is a @Composable that collects state with collectAsStateWithLifecycle() and calls ViewModel functions. No business logic lives here.
Domain (models + repository interfaces)Defines Product, CartLine, ProductRepository, and CartRepository. Add use cases such as PlaceOrder only when a rule is shared.
Data (Room + Retrofit + mappers)Implements the repository interfaces. Room handles cart persistence; Retrofit/OkHttp fetches products. Mappers convert DTOs and entities to domain models.
DI (Hilt modules)@Module with @Provides / @Binds wires Retrofit, Room, DAOs, and repository implementations, scoped @Singleton where one instance is needed.
Navigation (type-safe routes)@Serializable data object routes for screens without arguments and a data class ProductDetailRoute(val productId: String). A ViewModel reads its arguments with savedStateHandle.toRoute().

Milestones

1. Project scaffold, Hilt, and Navigation skeleton

Create a single-module project where Hilt is wired and a NavHost switches between placeholder screens.

  1. Create a new Compose project in Android Studio. Through the version catalog add hilt-android with its KSP compiler and Gradle plugin, hilt-navigation-compose, navigation-compose, the Kotlin serialization plugin, room-runtime and room-ktx with the Room KSP compiler, paging-compose, and retrofit.
  2. Add @HiltAndroidApp to the Application class (registered in the manifest) and @AndroidEntryPoint to the main Activity. Verify the app launches without a Hilt error.
  3. Define @Serializable routes: data object ProductListRoute, data class ProductDetailRoute(val productId: String), data object CartRoute, and data object CheckoutRoute. Build a NavHost with a composable<T> block for each that shows a Text placeholder.
  4. Add a Scaffold with a bottom NavigationBar for the top-level destinations (products and cart). Open the detail screen from a placeholder button with navController.navigate(ProductDetailRoute("1")).
  5. Run the app and tap through every screen. Confirm back navigation works.

Done when: The app launches, Hilt injects without error, and you can navigate forward and back across all placeholder screens.

Lessons: hilt basics, navigation in compose, convention plugins and version catalogs

2. Product list with Paging 3

Replace the product-list placeholder with a LazyColumn that loads products from a REST API through Paging 3.

  1. Define a Product domain model and a ProductDto. Write a Retrofit interface with @GET("products") suspend fun getProducts(@Query("page") page: Int, @Query("size") size: Int): ProductPageDto.
  2. Implement ProductPagingSource : PagingSource<Int, Product>: call the endpoint in load(), map DTOs to Product, return LoadResult.Page with prevKey/nextKey (null at the ends), return LoadResult.Error for IOException and HttpException, and implement getRefreshKey.
  3. In ProductListViewModel, expose val products: Flow<PagingData<Product>> = Pager(PagingConfig(pageSize = 20)) { ProductPagingSource(api) }.flow.cachedIn(viewModelScope). Create a new PagingSource in the factory lambda every time; do not convert PagingData to a StateFlow.
  4. In the screen, call collectAsLazyPagingItems() and render items with items(count = items.itemCount, key = items.itemKey { it.id }). Show a spinner for LoadState.Loading and a retry row calling items.retry() for LoadState.Error.
  5. Test the PagingSource with a fake API: assert that load() returns the expected page and keys, and that an IOException becomes LoadResult.Error.

Done when: Scrolling the product list loads additional pages, an error shows a working retry row, and no duplicate items appear after scrolling back up or rotating.

Lessons: paging 3, retrofit and okhttp, flow operators

3. Product detail and add-to-cart

Show a product detail screen and let the user add an item to the cart, which writes to Room.

  1. Build ProductDetailViewModel. It reads savedStateHandle.toRoute<ProductDetailRoute>().productId, loads the product, and exposes a StateFlow<DetailUiState>.
  2. Define a CartItem Room entity with productId (primary key), name, priceCents: Long, quantity, and addedAt. Store money as whole cents, never as Double.
  3. Write CartItemDao with observeAll(): Flow<List<CartItem>> and a @Transaction add(item) that increments the quantity of an existing row or inserts a new one (see Key code).
  4. Create a CartRepository interface and a RoomCartRepository implementation that maps entities to CartLine. Bind it with @Binds in a Hilt module.
  5. Add addToCart() to ProductDetailViewModel. When the write finishes, set userMessage = "Added to cart" in the UI state; the screen shows a Snackbar and then calls userMessageShown().

Done when: Tapping a product opens its detail screen. Adding the same product twice gives one row with quantity 2, and the item shows on the cart screen.

Lessons: viewmodel and ui state, room entities daos queries, one off events done right

4. Cart screen backed by Room

Display the cart with quantity steppers that write to Room, and let Room's Flow drive the UI.

  1. Build CartViewModel that maps cartRepository.observeCart() to a CartUiState (lines plus total in cents) with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), CartUiState()).
  2. Implement increment(productId) and decrement(productId) that call changeQuantity(productId, delta). The DAO runs UPDATE ... SET quantity = quantity + :delta and deletes the row when the quantity reaches zero, in one transaction.
  3. In the cart screen, render a LazyColumn with key = { it.productId }, a minus/plus stepper per row, and the formatted total at the bottom. Add a checkout button that navigates to CheckoutRoute.
  4. Add items, force-stop the app, and relaunch. Confirm the cart is restored from Room.
  5. Write CartViewModelTest with a fake CartRepository backed by a MutableStateFlow: assert the total updates after increment, and that decrement on quantity 1 removes the line.

Done when: Steppers update the cart immediately, rapid taps never lose an update, a force-stop and relaunch shows the same cart, and the ViewModel tests pass.

Lessons: single source of truth, stateflow and sharedflow, testing coroutines and flows

5. Checkout form with validation and SavedStateHandle

Build a multi-field checkout form that validates input, survives process death, and calls a mock order endpoint.

  1. In CheckoutViewModel, read name, email, and address with savedStateHandle.getStateFlow(key, "") and write them with savedStateHandle[key] = value. Keep the card number only in a private MutableStateFlow, so it is never written to saved state; the user re-enters it after process death, as real payment forms do.
  2. Combine the fields into a CheckoutUiState with per-field errors: non-blank name, a basic email check, a non-blank address, and a card number of 13 to 19 digits that passes a Luhn check. Disable the submit button until the form is valid.
  3. On submit, call a mock placeOrder(request: OrderRequest): Result<OrderConfirmation> from viewModelScope, and show a loading indicator while it runs.
  4. On success, set placedOrderId in the UI state. In the screen, a LaunchedEffect(state.placedOrderId) navigates to the confirmation screen (popping checkout off the back stack) and calls viewModel.orderNavigationHandled(), which clears the field.
  5. Write CheckoutViewModelTest: construct the ViewModel with SavedStateHandle(mapOf("name" to "Ada")) to simulate restoration after process death and assert the field is restored; assert that submit is blocked while a field is invalid.

Done when: Typed values survive rotation and process death (test with "Don't keep activities" or adb shell am kill while backgrounded). Invalid fields show errors. A valid submit navigates to the confirmation screen exactly once.

Lessons: savedstatehandle and process death, error handling and result types, collecting flows safely in the ui

6. Tests, performance pass, and final review

Add Compose UI tests, check recomposition, and review the whole project.

  1. Write a CartScreenTest with createComposeRule(): set the stateless cart content with a fixed CartUiState, assert the rows and total are shown, and assert that tapping plus calls the onIncrement lambda with the right productId.
  2. Write a CheckoutScreenTest that types into each field, asserts error text appears for an invalid email, and asserts the submit button is disabled until the form is valid.
  3. Enable Compose compiler reports in the composeCompiler Gradle block. Read composables.txt and Layout Inspector's recomposition counts; fix real problems such as a list rebuilt in the composable body, and only mark a class @Immutable when it truly is.
  4. Run ./gradlew test and ./gradlew connectedCheck. Replace any Thread.sleep or real delays in tests with runTest virtual time or composeRule.waitUntil.
  5. Self-review: no GlobalScope, coroutines scoped to viewModelScope or the UI lifecycle, and no ViewModel holding an Activity, View, or Context.

Done when: All unit and UI tests pass, recomposition counts look sane while scrolling and tapping steppers, and no GlobalScope or Context leaks remain.

Lessons: compose ui tests, viewmodel tests, recomposition and stability

Key code

@Entity(tableName = "cart_items")
data class CartItem(
    @PrimaryKey val productId: String,
    val name: String,
    val priceCents: Long,
    val quantity: Int,
    val addedAt: Long,
)
 
@Dao
abstract class CartItemDao {
    @Query("SELECT * FROM cart_items ORDER BY addedAt")
    abstract fun observeAll(): Flow<List<CartItem>>
 
    @Insert
    abstract suspend fun insert(item: CartItem)
 
    @Query("UPDATE cart_items SET quantity = quantity + :delta WHERE productId = :productId")
    abstract suspend fun addToQuantity(productId: String, delta: Int): Int
 
    @Query("DELETE FROM cart_items WHERE productId = :productId AND quantity <= 0")
    abstract suspend fun deleteIfEmpty(productId: String)
 
    @Transaction
    open suspend fun add(item: CartItem) {
        if (addToQuantity(item.productId, item.quantity) == 0) insert(item)
    }
 
    @Transaction
    open suspend fun changeQuantity(productId: String, delta: Int) {
        addToQuantity(productId, delta)
        deleteIfEmpty(productId)
    }
}
 
data class CartLine(val productId: String, val name: String, val priceCents: Long, val quantity: Int)
 
interface CartRepository {
    fun observeCart(): Flow<List<CartLine>>
    suspend fun changeQuantity(productId: String, delta: Int)
}
 
class RoomCartRepository @Inject constructor(private val dao: CartItemDao) : CartRepository {
    override fun observeCart(): Flow<List<CartLine>> = dao.observeAll().map { rows ->
        rows.map { CartLine(it.productId, it.name, it.priceCents, it.quantity) }
    }
 
    override suspend fun changeQuantity(productId: String, delta: Int) =
        dao.changeQuantity(productId, delta)
}
 
data class CartUiState(val lines: List<CartLine> = emptyList()) {
    val totalCents: Long get() = lines.sumOf { it.priceCents * it.quantity }
}
 
@HiltViewModel
class CartViewModel @Inject constructor(
    private val cartRepository: CartRepository,
) : ViewModel() {
 
    val uiState: StateFlow<CartUiState> = cartRepository.observeCart()
        .map { CartUiState(it) }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), CartUiState())
 
    fun increment(productId: String) = changeQuantity(productId, 1)
    fun decrement(productId: String) = changeQuantity(productId, -1)
 
    private fun changeQuantity(productId: String, delta: Int) {
        viewModelScope.launch { cartRepository.changeQuantity(productId, delta) }
    }
}
  • Room is the single source of truth: the ViewModel never keeps its own copy of the cart. A write makes the DAO's Flow re-emit, and the UI follows. After process death the same query rebuilds the screen.
  • Relative, atomic updates: the stepper sends a delta, and SQL computes quantity + :delta inside a @Transaction. Two fast taps cannot overwrite each other the way a read-modify-write of an absolute quantity can.
  • Main-safe without dispatchers: Room runs suspend DAO functions and Flow queries off the main thread, so viewModelScope.launch needs no Dispatchers.IO.
  • WhileSubscribed(5_000) keeps the upstream alive through a rotation but stops collecting Room a few seconds after the user leaves the screen.
  • Money as Long cents avoids floating-point rounding in totals; format it only in the UI.

Pitfalls

  • Collecting with collectAsState() instead of collectAsStateWithLifecycle(). collectAsState() keeps collecting while the app is in the background, so upstream work (Room queries, WhileSubscribed timers) never stops. Fix: use collectAsStateWithLifecycle() from lifecycle-runtime-compose so collection stops below the STARTED state.
  • Keeping checkout fields in remember { mutableStateOf(...) }. remember is lost on rotation and on process death, so the user loses typed input. Fix: keep form state in the ViewModel and back the restorable fields with SavedStateHandle.
  • Writing the card number to SavedStateHandle. Saved state is serialized into a Bundle that the system keeps outside your process, which is the wrong place for payment data. Fix: keep it in memory only and let the user re-enter it; real apps hand card entry to the payment provider's SDK.
  • Navigating from a success flag that is never cleared. A LaunchedEffect keyed on orderPlaced = true fires again after rotation or when the user comes back, so the app navigates twice. Fix: clear the field through orderNavigationHandled() after navigating, or use a Channel and accept that it can lose an event if the collector is cancelled at the wrong moment.
  • Converting PagingData to a StateFlow or collecting it without cachedIn. PagingData is a one-shot stream; collecting it twice or after a configuration change without cachedIn(viewModelScope) throws or reloads from page one. Fix: expose Flow<PagingData<T>> with cachedIn and collect it with collectAsLazyPagingItems().
  • LazyColumn rows without stable keys. When an item is removed, rows below it are matched by position, so remembered row state shifts to the wrong product and every row below recomposes. Fix: pass key = { it.productId } for the cart and items.itemKey { it.id } for the paged list.
  • Starting the order call from rememberCoroutineScope(). That scope is cancelled when the screen leaves composition, including on rotation, so the order request can be cancelled mid-flight. Fix: start it from a ViewModel function with viewModelScope.

Code review finding

Fast taps on the stepper lose quantity updates
  • The first version had updateQuantity(productId, newQty), where the screen computed newQty = line.quantity + 1 from the state it was showing.
  • Two taps before Room re-emitted both read quantity 2 and both wrote 3, so the cart showed 3 instead of 4.
  • The same read-modify-write existed in addToCart: it read the row, added one, and called @Upsert, so a double tap on "Add to cart" also lost an update.
  • The ViewModel test did not catch it because it awaited each call before the next one.
The fix
  • Send a delta instead of an absolute value: increment(productId) and decrement(productId) call changeQuantity(productId, delta).
  • Let SQLite do the arithmetic with UPDATE cart_items SET quantity = quantity + :delta, and delete rows that reach zero, inside one DAO @Transaction.
  • Use the same pattern for add(): increment the existing row and insert only when no row was updated.
  • Add an instrumented DAO test with an in-memory database that launches two changeQuantity(id, 1) calls concurrently and asserts the quantity went up by two.

Stretch goals

  • Add a search bar to the product list that filters via a debounced API call, and show how a new query creates a new Pager and resets the keys.
  • Add a RemoteMediator that caches product pages in Room so the list works offline.
  • Add screenshot tests for the product list, cart, and checkout screens with Compose Preview Screenshot Testing or Roborazzi.
  • Split the project into :app, :core:data, :core:model, :feature:catalog, :feature:cart, and :feature:checkout modules with convention plugins for Compose, Hilt, and test dependencies.
  • Add a DataStore<Preferences> layer to remember the last shipping address and pre-fill the checkout form on return visits.

Done checklist

  • Every ViewModel function is covered by a test with a fake repository and runTest; no real network calls run in unit tests.
  • The cart survives a force-stop and relaunch, and rapid stepper taps never lose an update.
  • Name, email, and address survive rotation and process death; the card number is never written to saved state.
  • One-off events (snackbar, navigation after an order) fire exactly once, including after rotation.
  • PagingData is exposed as a Flow with cachedIn(viewModelScope) and collected with collectAsLazyPagingItems(); the list shows no duplicates after scrolling back or rotating.
  • Lazy lists use stable keys, and money is stored and summed as Long cents.
  • Network failures become LoadState.Error or a Result failure with a visible message; no uncaught exception reaches the UI.
  • ./gradlew assembleDebug, ./gradlew test, and ./gradlew connectedCheck pass.

Talking about it in an interview

  • Explain why Room, not an in-memory StateFlow, is the cart's source of truth: it survives process death, every screen sees the same data, and there is nothing to roll back or reconcile.
  • Walk through the lost-update bug and the fix: relative SQL updates inside a @Transaction instead of read-modify-write with absolute values.
  • Talk about SavedStateHandle vs. remember for the checkout form, and why you chose not to persist the card number in saved state at all.
  • Discuss the Paging 3 decisions: a fresh PagingSource per Pager invalidation, cachedIn(viewModelScope), collectAsLazyPagingItems(), stable item keys, and retry through LoadState.
  • Describe how you model one-off events as UI state the screen acknowledges, and where a Channel or SharedFlow could lose or repeat an event.