refactor(android): adopt MVVM (UiState + ShopViewModel) for lesson 7
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled

This commit is contained in:
xiaobai committed 2026-03-04 18:08:58 +08:00
1 parent 348f34d610
commit 3c211d731a
2 files changed
+188 -101

No files matched your search

@@ -37,12 +37,8 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
@@ -53,70 +49,19 @@ import androidx.compose.ui.unit.dp
import coil3.compose.SubcomposeAsyncImage import coil3.compose.SubcomposeAsyncImage
import coil3.compose.SubcomposeAsyncImageContent import coil3.compose.SubcomposeAsyncImageContent
import com.example.minishop.cart.CartItem import com.example.minishop.cart.CartItem
import com.example.minishop.cart.CartRepository
import com.example.minishop.checkout.CheckoutService
import com.example.minishop.model.Product import com.example.minishop.model.Product
import com.example.minishop.network.ProductApi
import com.example.minishop.repository.ProductRepository
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
private enum class Tab { Home, Cart } enum class Tab { Home, Cart }
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun App() { fun App() {
MaterialTheme { MaterialTheme {
val scope = rememberCoroutineScope()
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
val productRepository = remember { val vm: ShopViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
ProductRepository( val ui = vm.uiState
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
)
}
val cartRepository = remember { CartRepository() }
val checkoutService = remember { CheckoutService(cartRepository) }
var currentTab by remember { mutableStateOf(Tab.Home) }
var selected by remember { mutableStateOf<Product?>(null) }
var inDetail by remember { mutableStateOf(false) }
var query by remember { mutableStateOf("") }
var products by remember { mutableStateOf<List<Product>>(emptyList()) }
var loading by remember { mutableStateOf(false) }
var loadError by remember { mutableStateOf<String?>(null) }
var tick by remember { mutableStateOf(0) }
fun loadProducts() {
scope.launch {
loading = true
loadError = null
val list = runCatching { productRepository.getProducts() }
.onFailure { loadError = it.message ?: "加载失败" }
.getOrDefault(emptyList())
products = list
loading = false
}
}
LaunchedEffect(Unit) { loadProducts() }
val normalizedQuery = remember(query) { query.trim() }
val filteredProducts = remember(products, normalizedQuery) {
if (normalizedQuery.isBlank()) {
products
} else {
products.filter {
it.title.contains(normalizedQuery, ignoreCase = true) ||
it.description.contains(normalizedQuery, ignoreCase = true)
}
}
}
val cartItems = remember(tick) { cartRepository.items() }
val productMap = remember(products) { products.associateBy { it.id } }
val totalCount = remember(cartItems) { cartItems.sumOf { it.quantity } }
val totalPrice = remember(cartItems, products) { checkoutService.totalPrice(productMap) }
Scaffold( Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) }, snackbarHost = { SnackbarHost(snackbarHostState) },
@@ -125,18 +70,18 @@ fun App() {
title = { title = {
Text( Text(
when { when {
inDetail -> "商品详情" ui.inDetail -> "商品详情"
currentTab == Tab.Home -> "KMP Mini Shopping" ui.currentTab == Tab.Home -> "KMP Mini Shopping"
else -> "购物车" else -> "购物车"
} }
) )
}, },
actions = { actions = {
if (inDetail) { if (ui.inDetail) {
TextButton(onClick = { inDetail = false }) { Text("返回") } TextButton(onClick = { vm.closeDetail() }) { Text("返回") }
} else { } else {
Text( Text(
text = "共 $totalCount 件", text = "共 ${ui.totalCount} 件",
style = MaterialTheme.typography.labelLarge, style = MaterialTheme.typography.labelLarge,
modifier = Modifier.padding(end = 12.dp) modifier = Modifier.padding(end = 12.dp)
) )
@@ -145,19 +90,19 @@ fun App() {
) )
}, },
bottomBar = { bottomBar = {
if (!inDetail) { if (!ui.inDetail) {
NavigationBar { NavigationBar {
NavigationBarItem( NavigationBarItem(
selected = currentTab == Tab.Home, selected = ui.currentTab == Tab.Home,
onClick = { currentTab = Tab.Home }, onClick = { vm.selectTab(Tab.Home) },
icon = { Text("🏠") }, icon = { Text("🏠") },
label = { Text("商品") } label = { Text("商品") }
) )
NavigationBarItem( NavigationBarItem(
selected = currentTab == Tab.Cart, selected = ui.currentTab == Tab.Cart,
onClick = { currentTab = Tab.Cart }, onClick = { vm.selectTab(Tab.Cart) },
icon = { Text("🛒") }, icon = { Text("🛒") },
label = { Text("购物车($totalCount)") } label = { Text("购物车(${ui.totalCount})") }
) )
} }
} }
@@ -170,47 +115,45 @@ fun App() {
.background(MaterialTheme.colorScheme.surface) .background(MaterialTheme.colorScheme.surface)
) { ) {
when { when {
inDetail -> ProductDetailScreen( ui.inDetail -> ProductDetailScreen(
product = selected, product = vm.selectedProduct,
quantity = selected?.let { p -> cartItems.firstOrNull { it.productId == p.id }?.quantity } ?: 0, quantity = vm.selectedProduct?.let { vm.quantityOf(it.id) } ?: 0,
onAdd = { onAdd = {
cartRepository.add(it.id) val msg = vm.addToCart(it.id)
tick++ scope.launch {
scope.launch { snackbarHostState.showSnackbar("已加入购物车") } snackbarHostState.showSnackbar(msg)
}
} }
) )
currentTab == Tab.Home -> ProductListScreen( ui.currentTab == Tab.Home -> ProductListScreen(
loading = loading, loading = ui.loading,
error = loadError, error = ui.loadError,
products = filteredProducts, products = vm.filteredProducts,
totalProducts = products.size, totalProducts = ui.products.size,
query = query, query = ui.query,
quantityOf = { id -> cartItems.firstOrNull { it.productId == id }?.quantity ?: 0 }, quantityOf = vm::quantityOf,
onQueryChange = { query = it }, onQueryChange = vm::onQueryChange,
onRetry = { loadProducts() }, onRetry = vm::refreshProducts,
onAdd = { onAdd = {
cartRepository.add(it.id) vm.addToCart(it.id)
tick++
}, },
onClick = { onClick = vm::openDetail
selected = it
inDetail = true
}
) )
else -> CartScreen( else -> CartScreen(
items = cartItems, items = ui.cartItems,
productMap = productMap, productMap = ui.products.associateBy { it.id },
totalPrice = totalPrice, totalPrice = ui.totalPrice,
onInc = { id -> cartRepository.increase(id); tick++ }, onInc = vm::increase,
onDec = { id -> cartRepository.decrease(id); tick++ }, onDec = vm::decrease,
onRemove = { id -> cartRepository.remove(id); tick++ }, onRemove = vm::remove,
onClear = { cartRepository.clear(); tick++ }, onClear = vm::clear,
onCheckout = { onCheckout = {
val result = checkoutService.checkout(productMap) val msg = vm.checkout()
tick++ scope.launch {
scope.launch { snackbarHostState.showSnackbar(result.message) } snackbarHostState.showSnackbar(msg)
}
} }
) )
} }
@@ -219,6 +162,7 @@ fun App() {
} }
} }
@Composable @Composable
private fun ProductListScreen( private fun ProductListScreen(
loading: Boolean, loading: Boolean,
@@ -0,0 +1,143 @@
package com.example.minishop
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.example.minishop.cart.CartItem
import com.example.minishop.cart.CartRepository
import com.example.minishop.checkout.CheckoutService
import com.example.minishop.model.Product
import com.example.minishop.network.ProductApi
import com.example.minishop.repository.ProductRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
data class ShopUiState(
val currentTab: Tab = Tab.Home,
val inDetail: Boolean = false,
val selectedProductId: String? = null,
val query: String = "",
val products: List<Product> = emptyList(),
val loading: Boolean = false,
val loadError: String? = null,
val cartItems: List<CartItem> = emptyList(),
val totalCount: Int = 0,
val totalPrice: Double = 0.0
)
class ShopViewModel : ViewModel() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private val productRepository = ProductRepository(
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
)
private val cartRepository = CartRepository()
private val checkoutService = CheckoutService(cartRepository)
var uiState by mutableStateOf(ShopUiState())
private set
val filteredProducts: List<Product>
get() {
val normalized = uiState.query.trim()
return if (normalized.isBlank()) {
uiState.products
} else {
uiState.products.filter {
it.title.contains(normalized, ignoreCase = true) ||
it.description.contains(normalized, ignoreCase = true)
}
}
}
val selectedProduct: Product?
get() = uiState.products.firstOrNull { it.id == uiState.selectedProductId }
init {
refreshProducts()
syncCart()
}
fun refreshProducts() {
scope.launch {
uiState = uiState.copy(loading = true, loadError = null)
val list = runCatching { productRepository.getProducts() }
.onFailure { uiState = uiState.copy(loadError = it.message ?: "加载失败") }
.getOrDefault(emptyList())
uiState = uiState.copy(products = list, loading = false)
syncCart()
}
}
fun onQueryChange(value: String) {
uiState = uiState.copy(query = value)
}
fun selectTab(tab: Tab) {
uiState = uiState.copy(currentTab = tab)
}
fun openDetail(product: Product) {
uiState = uiState.copy(inDetail = true, selectedProductId = product.id)
}
fun closeDetail() {
uiState = uiState.copy(inDetail = false)
}
fun quantityOf(productId: String): Int =
uiState.cartItems.firstOrNull { it.productId == productId }?.quantity ?: 0
fun addToCart(productId: String): String {
cartRepository.add(productId)
syncCart()
return "已加入购物车"
}
fun increase(productId: String) {
cartRepository.increase(productId)
syncCart()
}
fun decrease(productId: String) {
cartRepository.decrease(productId)
syncCart()
}
fun remove(productId: String) {
cartRepository.remove(productId)
syncCart()
}
fun clear() {
cartRepository.clear()
syncCart()
}
fun checkout(): String {
val productMap = uiState.products.associateBy { it.id }
val result = checkoutService.checkout(productMap)
syncCart()
return result.message
}
private fun syncCart() {
val items = cartRepository.items()
val productMap = uiState.products.associateBy { it.id }
uiState = uiState.copy(
cartItems = items,
totalCount = items.sumOf { it.quantity },
totalPrice = checkoutService.totalPrice(productMap)
)
}
override fun onCleared() {
scope.cancel()
super.onCleared()
}
}