feat: add lesson 7 minimal mvi for product list
This commit is contained in:
1 parent
e42597b8b7
commit
9dfe6747dd
3 files changed
+345
-32
No files matched your search
@@ -50,6 +50,7 @@ import coil3.compose.SubcomposeAsyncImage
|
||||
import coil3.compose.SubcomposeAsyncImageContent
|
||||
import com.example.minishop.cart.CartItem
|
||||
import com.example.minishop.model.Product
|
||||
import com.example.minishop.order.ShopOrder
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
enum class Tab { Home, Cart, Orders }
|
||||
@@ -134,16 +135,18 @@ fun App() {
|
||||
)
|
||||
|
||||
ui.currentTab == Tab.Home -> ProductListScreen(
|
||||
loading = ui.loading,
|
||||
error = ui.loadError,
|
||||
state = ui.productListState,
|
||||
products = vm.filteredProducts,
|
||||
totalProducts = ui.products.size,
|
||||
query = ui.query,
|
||||
quantityOf = vm::quantityOf,
|
||||
onQueryChange = vm::onQueryChange,
|
||||
onRetry = vm::refreshProducts,
|
||||
onRetry = { vm.dispatch(ProductListIntent.Retry) },
|
||||
onAdd = {
|
||||
vm.addToCart(it)
|
||||
val msg = vm.addToCart(it)
|
||||
scope.launch {
|
||||
snackbarHostState.showSnackbar(msg)
|
||||
}
|
||||
},
|
||||
onClick = vm::openDetail
|
||||
)
|
||||
@@ -170,11 +173,9 @@ fun App() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun ProductListScreen(
|
||||
loading: Boolean,
|
||||
error: String?,
|
||||
state: ProductListState,
|
||||
products: List<Product>,
|
||||
totalProducts: Int,
|
||||
query: String,
|
||||
@@ -205,18 +206,21 @@ private fun ProductListScreen(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
|
||||
when {
|
||||
loading -> EmptyState("⏳ 加载中...")
|
||||
error != null -> {
|
||||
when (state) {
|
||||
ProductListState.Loading -> EmptyState("⏳ 加载中...")
|
||||
|
||||
is ProductListState.Error -> {
|
||||
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)) {
|
||||
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("加载失败:$error", color = MaterialTheme.colorScheme.onErrorContainer)
|
||||
Text("加载失败:${state.message}", color = MaterialTheme.colorScheme.onErrorContainer)
|
||||
Button(onClick = onRetry) { Text("重试") }
|
||||
}
|
||||
}
|
||||
}
|
||||
products.isEmpty() -> EmptyState("没有匹配的商品")
|
||||
else -> {
|
||||
|
||||
ProductListState.Empty -> EmptyState("没有匹配的商品")
|
||||
|
||||
is ProductListState.Success -> {
|
||||
LazyVerticalStaggeredGrid(
|
||||
columns = StaggeredGridCells.Fixed(2),
|
||||
verticalItemSpacing = 10.dp,
|
||||
@@ -368,7 +372,7 @@ private fun CartScreen(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OrderScreen(orders: List<com.example.minishop.order.ShopOrder>) {
|
||||
private fun OrderScreen(orders: List<ShopOrder>) {
|
||||
if (orders.isEmpty()) {
|
||||
EmptyState("还没有订单")
|
||||
return
|
||||
|
||||
@@ -19,14 +19,27 @@ import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
sealed interface ProductListIntent {
|
||||
data object Load : ProductListIntent
|
||||
data object Retry : ProductListIntent
|
||||
data class AddToCart(val product: Product) : ProductListIntent
|
||||
data class Search(val query: String) : ProductListIntent
|
||||
}
|
||||
|
||||
sealed interface ProductListState {
|
||||
data object Loading : ProductListState
|
||||
data class Success(val products: List<Product>) : ProductListState
|
||||
data class Error(val message: String) : ProductListState
|
||||
data object Empty : ProductListState
|
||||
}
|
||||
|
||||
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 productListState: ProductListState = ProductListState.Loading,
|
||||
val cartItems: List<CartItem> = emptyList(),
|
||||
val totalCount: Int = 0,
|
||||
val totalPrice: Double = 0.0,
|
||||
@@ -64,25 +77,53 @@ class ShopViewModel : ViewModel() {
|
||||
get() = uiState.products.firstOrNull { it.id == uiState.selectedProductId }
|
||||
|
||||
init {
|
||||
refreshProducts()
|
||||
dispatch(ProductListIntent.Load)
|
||||
syncCart()
|
||||
syncOrders()
|
||||
}
|
||||
|
||||
fun dispatch(intent: ProductListIntent) {
|
||||
when (intent) {
|
||||
ProductListIntent.Load,
|
||||
ProductListIntent.Retry -> refreshProducts()
|
||||
|
||||
is ProductListIntent.Search -> {
|
||||
uiState = uiState.copy(query = intent.query)
|
||||
}
|
||||
|
||||
is ProductListIntent.AddToCart -> {
|
||||
cartRepository.add(intent.product)
|
||||
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(productListState = ProductListState.Loading)
|
||||
|
||||
uiState = uiState.copy(products = list, loading = false)
|
||||
syncCart()
|
||||
runCatching { productRepository.getProducts() }
|
||||
.onSuccess { list ->
|
||||
uiState = uiState.copy(
|
||||
products = list,
|
||||
productListState = if (list.isEmpty()) {
|
||||
ProductListState.Empty
|
||||
} else {
|
||||
ProductListState.Success(list)
|
||||
}
|
||||
)
|
||||
syncCart()
|
||||
}
|
||||
.onFailure {
|
||||
uiState = uiState.copy(
|
||||
productListState = ProductListState.Error(it.message ?: "加载失败")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun onQueryChange(value: String) {
|
||||
uiState = uiState.copy(query = value)
|
||||
dispatch(ProductListIntent.Search(value))
|
||||
}
|
||||
|
||||
fun selectTab(tab: Tab) {
|
||||
@@ -101,8 +142,7 @@ class ShopViewModel : ViewModel() {
|
||||
uiState.cartItems.firstOrNull { it.productId == productId }?.quantity ?: 0
|
||||
|
||||
fun addToCart(product: Product): String {
|
||||
cartRepository.add(product)
|
||||
syncCart()
|
||||
dispatch(ProductListIntent.AddToCart(product))
|
||||
return "已加入购物车"
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user