Skip to content

Commit 54efca6

Browse files
committed
Refactor: Calculate total cart items in ViewModel
This commit refactors the calculation of the total number of items in the cart. Previously, the total item count was calculated independently in both the Android `CartScreen.kt` and iOS `CartView.swift`. This change moves the calculation into the shared `CartViewModel.kt`. A new `totalItemCount` property is added to `CartUiState`, which is now populated within the `map` function that transforms the `repository.cartDetails` flow. This centralization simplifies the UI components and ensures consistency in how the total item count is determined across platforms.
1 parent b1270ef commit 54efca6

File tree

3 files changed

+9
-4
lines changed

3 files changed

+9
-4
lines changed

Fruitties/androidApp/src/main/java/com/example/fruitties/android/ui/CartScreen.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ fun CartScreen(onNavBarBack: () -> Unit) {
108108
.padding(paddingValues)
109109
.padding(16.dp),
110110
) {
111-
val cartItemCount = cartState.cartDetails.sumOf { it.count }
111+
val cartItemCount = cartState.totalItemCount
112112
Text(
113113
text = "Cart has $cartItemCount items",
114114
modifier = Modifier.padding(8.dp),

Fruitties/iosApp/iosApp/CartView.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ struct CartView : View {
2929
Observing(cartViewModel.cartUiState) { cartUIState in
3030
VStack {
3131
HStack {
32-
let total = cartUIState.cartDetails.reduce(0) { $0 + $1.count }
32+
let total = cartUIState.totalItemCount
3333
Text("Cart has \(total) items").padding()
3434
Spacer()
3535
}

Fruitties/shared/src/commonMain/kotlin/com/example/fruitties/viewmodel/CartViewModel.kt

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,12 @@ class CartViewModel(
3636
) : ViewModel() {
3737
val cartUiState: StateFlow<CartUiState> =
3838
repository.cartDetails
39-
.map { CartUiState(it) }
40-
.stateIn(
39+
.map { details ->
40+
CartUiState(
41+
cartDetails = details,
42+
totalItemCount = details.sumOf { it.count },
43+
)
44+
}.stateIn(
4145
scope = viewModelScope,
4246
started = SharingStarted.WhileSubscribed(TIMEOUT_MILLIS),
4347
initialValue = CartUiState(),
@@ -66,6 +70,7 @@ class CartViewModel(
6670
*/
6771
data class CartUiState(
6872
val cartDetails: List<CartItemDetails> = listOf(),
73+
val totalItemCount: Int = 0,
6974
)
7075

7176
private const val TIMEOUT_MILLIS = 5_000L

0 commit comments

Comments
 (0)