refactor(android): adopt MVVM (UiState + ShopViewModel) for lesson 7
This commit is contained in:
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.TopAppBar
|
||||
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.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
@@ -53,70 +49,19 @@ import androidx.compose.ui.unit.dp
|
||||
import coil3.compose.SubcomposeAsyncImage
|
||||
import coil3.compose.SubcomposeAsyncImageContent
|
||||
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.launch
|
||||
|
||||
private enum class Tab { Home, Cart }
|
||||
enum class Tab { Home, Cart }
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun App() {
|
||||
MaterialTheme {
|
||||
val scope = rememberCoroutineScope()
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
|
||||
val productRepository = remember {
|
||||
ProductRepository(
|
||||
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) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val vm: ShopViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
|
||||
val ui = vm.uiState
|
||||
|
||||
Scaffold(
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
@@ -125,18 +70,18 @@ fun App() {
|
||||
title = {
|
||||
Text(
|
||||
when {
|
||||
inDetail -> "商品详情"
|
||||
currentTab == Tab.Home -> "KMP Mini Shopping"
|
||||
ui.inDetail -> "商品详情"
|
||||
ui.currentTab == Tab.Home -> "KMP Mini Shopping"
|
||||
else -> "购物车"
|
||||
}
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
if (inDetail) {
|
||||
TextButton(onClick = { inDetail = false }) { Text("返回") }
|
||||
if (ui.inDetail) {
|
||||
TextButton(onClick = { vm.closeDetail() }) { Text("返回") }
|
||||
} else {
|
||||
Text(
|
||||
text = "共 $totalCount 件",
|
||||
text = "共 ${ui.totalCount} 件",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier.padding(end = 12.dp)
|
||||
)
|
||||
@@ -145,19 +90,19 @@ fun App() {
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
if (!inDetail) {
|
||||
if (!ui.inDetail) {
|
||||
NavigationBar {
|
||||
NavigationBarItem(
|
||||
selected = currentTab == Tab.Home,
|
||||
onClick = { currentTab = Tab.Home },
|
||||
selected = ui.currentTab == Tab.Home,
|
||||
onClick = { vm.selectTab(Tab.Home) },
|
||||
icon = { Text("🏠") },
|
||||
label = { Text("商品") }
|
||||
)
|
||||
NavigationBarItem(
|
||||
selected = currentTab == Tab.Cart,
|
||||
onClick = { currentTab = Tab.Cart },
|
||||
selected = ui.currentTab == Tab.Cart,
|
||||
onClick = { vm.selectTab(Tab.Cart) },
|
||||
icon = { Text("🛒") },
|
||||
label = { Text("购物车($totalCount)") }
|
||||
label = { Text("购物车(${ui.totalCount})") }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -170,47 +115,45 @@ fun App() {
|
||||
.background(MaterialTheme.colorScheme.surface)
|
||||
) {
|
||||
when {
|
||||
inDetail -> ProductDetailScreen(
|
||||
product = selected,
|
||||
quantity = selected?.let { p -> cartItems.firstOrNull { it.productId == p.id }?.quantity } ?: 0,
|
||||
ui.inDetail -> ProductDetailScreen(
|
||||
product = vm.selectedProduct,
|
||||
quantity = vm.selectedProduct?.let { vm.quantityOf(it.id) } ?: 0,
|
||||
onAdd = {
|
||||
cartRepository.add(it.id)
|
||||
tick++
|
||||
scope.launch { snackbarHostState.showSnackbar("已加入购物车") }
|
||||
val msg = vm.addToCart(it.id)
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(msg)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
currentTab == Tab.Home -> ProductListScreen(
|
||||
loading = loading,
|
||||
error = loadError,
|
||||
products = filteredProducts,
|
||||
totalProducts = products.size,
|
||||
query = query,
|
||||
quantityOf = { id -> cartItems.firstOrNull { it.productId == id }?.quantity ?: 0 },
|
||||
onQueryChange = { query = it },
|
||||
onRetry = { loadProducts() },
|
||||
ui.currentTab == Tab.Home -> ProductListScreen(
|
||||
loading = ui.loading,
|
||||
error = ui.loadError,
|
||||
products = vm.filteredProducts,
|
||||
totalProducts = ui.products.size,
|
||||
query = ui.query,
|
||||
quantityOf = vm::quantityOf,
|
||||
onQueryChange = vm::onQueryChange,
|
||||
onRetry = vm::refreshProducts,
|
||||
onAdd = {
|
||||
cartRepository.add(it.id)
|
||||
tick++
|
||||
vm.addToCart(it.id)
|
||||
},
|
||||
onClick = {
|
||||
selected = it
|
||||
inDetail = true
|
||||
}
|
||||
onClick = vm::openDetail
|
||||
)
|
||||
|
||||
else -> CartScreen(
|
||||
items = cartItems,
|
||||
productMap = productMap,
|
||||
totalPrice = totalPrice,
|
||||
onInc = { id -> cartRepository.increase(id); tick++ },
|
||||
onDec = { id -> cartRepository.decrease(id); tick++ },
|
||||
onRemove = { id -> cartRepository.remove(id); tick++ },
|
||||
onClear = { cartRepository.clear(); tick++ },
|
||||
items = ui.cartItems,
|
||||
productMap = ui.products.associateBy { it.id },
|
||||
totalPrice = ui.totalPrice,
|
||||
onInc = vm::increase,
|
||||
onDec = vm::decrease,
|
||||
onRemove = vm::remove,
|
||||
onClear = vm::clear,
|
||||
onCheckout = {
|
||||
val result = checkoutService.checkout(productMap)
|
||||
tick++
|
||||
scope.launch { snackbarHostState.showSnackbar(result.message) }
|
||||
val msg = vm.checkout()
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(msg)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -219,6 +162,7 @@ fun App() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun ProductListScreen(
|
||||
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()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user