Shopping app with cart and checkout
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
@Serializableroutes andtoRoute() SavedStateHandlefor form state that survives process death- One-off events modelled as UI state the screen acknowledges
- Hilt dependency injection across layers
- ViewModel tests with
runTestand 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 layer | Responsibility |
|---|---|
| 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.
- Create a new Compose project in Android Studio. Through the version catalog add
hilt-androidwith its KSP compiler and Gradle plugin,hilt-navigation-compose,navigation-compose, the Kotlin serialization plugin,room-runtimeandroom-ktxwith the Room KSP compiler,paging-compose, andretrofit. - Add
@HiltAndroidAppto theApplicationclass (registered in the manifest) and@AndroidEntryPointto the mainActivity. Verify the app launches without a Hilt error. - Define
@Serializableroutes:data object ProductListRoute,data class ProductDetailRoute(val productId: String),data object CartRoute, anddata object CheckoutRoute. Build aNavHostwith acomposable<T>block for each that shows aTextplaceholder. - Add a
Scaffoldwith a bottomNavigationBarfor the top-level destinations (products and cart). Open the detail screen from a placeholder button withnavController.navigate(ProductDetailRoute("1")). - 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.
- Define a
Productdomain model and aProductDto. Write aRetrofitinterface with@GET("products") suspend fun getProducts(@Query("page") page: Int, @Query("size") size: Int): ProductPageDto. - Implement
ProductPagingSource : PagingSource<Int, Product>: call the endpoint inload(), map DTOs toProduct, returnLoadResult.PagewithprevKey/nextKey(null at the ends), returnLoadResult.ErrorforIOExceptionandHttpException, and implementgetRefreshKey. - In
ProductListViewModel, exposeval products: Flow<PagingData<Product>> = Pager(PagingConfig(pageSize = 20)) { ProductPagingSource(api) }.flow.cachedIn(viewModelScope). Create a newPagingSourcein the factory lambda every time; do not convertPagingDatato aStateFlow. - In the screen, call
collectAsLazyPagingItems()and render items withitems(count = items.itemCount, key = items.itemKey { it.id }). Show a spinner forLoadState.Loadingand a retry row callingitems.retry()forLoadState.Error. - Test the
PagingSourcewith a fake API: assert thatload()returns the expected page and keys, and that anIOExceptionbecomesLoadResult.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.
- Build
ProductDetailViewModel. It readssavedStateHandle.toRoute<ProductDetailRoute>().productId, loads the product, and exposes aStateFlow<DetailUiState>. - Define a
CartItemRoom entity withproductId(primary key),name,priceCents: Long,quantity, andaddedAt. Store money as whole cents, never asDouble. - Write
CartItemDaowithobserveAll(): Flow<List<CartItem>>and a@Transactionadd(item)that increments the quantity of an existing row or inserts a new one (see Key code). - Create a
CartRepositoryinterface and aRoomCartRepositoryimplementation that maps entities toCartLine. Bind it with@Bindsin a Hilt module. - Add
addToCart()toProductDetailViewModel. When the write finishes, setuserMessage = "Added to cart"in the UI state; the screen shows aSnackbarand then callsuserMessageShown().
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.
- Build
CartViewModelthat mapscartRepository.observeCart()to aCartUiState(lines plus total in cents) withstateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), CartUiState()). - Implement
increment(productId)anddecrement(productId)that callchangeQuantity(productId, delta). The DAO runsUPDATE ... SET quantity = quantity + :deltaand deletes the row when the quantity reaches zero, in one transaction. - In the cart screen, render a
LazyColumnwithkey = { it.productId }, a minus/plus stepper per row, and the formatted total at the bottom. Add a checkout button that navigates toCheckoutRoute. - Add items, force-stop the app, and relaunch. Confirm the cart is restored from Room.
- Write
CartViewModelTestwith a fakeCartRepositorybacked by aMutableStateFlow: assert the total updates afterincrement, and thatdecrementon 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.
- In
CheckoutViewModel, readname,email, andaddresswithsavedStateHandle.getStateFlow(key, "")and write them withsavedStateHandle[key] = value. Keep the card number only in a privateMutableStateFlow, so it is never written to saved state; the user re-enters it after process death, as real payment forms do. - Combine the fields into a
CheckoutUiStatewith 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. - On submit, call a mock
placeOrder(request: OrderRequest): Result<OrderConfirmation>fromviewModelScope, and show a loading indicator while it runs. - On success, set
placedOrderIdin the UI state. In the screen, aLaunchedEffect(state.placedOrderId)navigates to the confirmation screen (popping checkout off the back stack) and callsviewModel.orderNavigationHandled(), which clears the field. - Write
CheckoutViewModelTest: construct the ViewModel withSavedStateHandle(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.
- Write a
CartScreenTestwithcreateComposeRule(): set the stateless cart content with a fixedCartUiState, assert the rows and total are shown, and assert that tapping plus calls theonIncrementlambda with the rightproductId. - Write a
CheckoutScreenTestthat types into each field, asserts error text appears for an invalid email, and asserts the submit button is disabled until the form is valid. - Enable Compose compiler reports in the
composeCompilerGradle block. Readcomposables.txtand Layout Inspector's recomposition counts; fix real problems such as a list rebuilt in the composable body, and only mark a class@Immutablewhen it truly is. - Run
./gradlew testand./gradlew connectedCheck. Replace anyThread.sleepor real delays in tests withrunTestvirtual time orcomposeRule.waitUntil. - Self-review: no
GlobalScope, coroutines scoped toviewModelScopeor the UI lifecycle, and noViewModelholding anActivity,View, orContext.
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
Flowre-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 + :deltainside 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
suspendDAO functions andFlowqueries off the main thread, soviewModelScope.launchneeds noDispatchers.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
Longcents 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,WhileSubscribedtimers) never stops. Fix: usecollectAsStateWithLifecycle()fromlifecycle-runtime-composeso collection stops below theSTARTEDstate. - Keeping checkout fields in remember { mutableStateOf(...) }.
rememberis lost on rotation and on process death, so the user loses typed input. Fix: keep form state in theViewModeland back the restorable fields withSavedStateHandle. - Writing the card number to SavedStateHandle. Saved state is serialized into a
Bundlethat 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
LaunchedEffectkeyed onorderPlaced = truefires again after rotation or when the user comes back, so the app navigates twice. Fix: clear the field throughorderNavigationHandled()after navigating, or use aChanneland 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.
PagingDatais a one-shot stream; collecting it twice or after a configuration change withoutcachedIn(viewModelScope)throws or reloads from page one. Fix: exposeFlow<PagingData<T>>withcachedInand collect it withcollectAsLazyPagingItems(). - 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 anditems.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
ViewModelfunction withviewModelScope.
Code review finding
- The first version had
updateQuantity(productId, newQty), where the screen computednewQty = line.quantity + 1from 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.
- Send a delta instead of an absolute value:
increment(productId)anddecrement(productId)callchangeQuantity(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
Pagerand resets the keys. - Add a
RemoteMediatorthat 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:checkoutmodules 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
ViewModelfunction is covered by a test with a fake repository andrunTest; 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.
PagingDatais exposed as aFlowwithcachedIn(viewModelScope)and collected withcollectAsLazyPagingItems(); the list shows no duplicates after scrolling back or rotating.- Lazy lists use stable keys, and money is stored and summed as
Longcents. - Network failures become
LoadState.Erroror aResultfailure with a visible message; no uncaught exception reaches the UI. ./gradlew assembleDebug,./gradlew test, and./gradlew connectedCheckpass.
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
@Transactioninstead of read-modify-write with absolute values. - Talk about
SavedStateHandlevs.rememberfor 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
PagingSourceperPagerinvalidation,cachedIn(viewModelScope),collectAsLazyPagingItems(), stable item keys, and retry throughLoadState. - Describe how you model one-off events as UI state the screen acknowledges, and where a
ChannelorSharedFlowcould lose or repeat an event.