feat: add lesson 7 minimal mvi for product list
This commit is contained in:
1 parent
e42597b8b7
commit
9dfe6747dd
3 files changed
+344
-31
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)
|
||||
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 "已加入购物车"
|
||||
}
|
||||
|
||||
|
||||
+275
-6
@@ -1944,7 +1944,276 @@ private fun OrderScreen(orders: List<ShopOrder>) {
|
||||
|
||||
---
|
||||
|
||||
# 十一、本节整体顺序(重新整理后的主线)
|
||||
# 十一、Step 6:把商品列表页改成最小 MVI
|
||||
|
||||
## 本步目标
|
||||
这一步不是把整个项目都改造成 MVI,
|
||||
而是只挑一个最适合演示状态管理的页面:**商品列表页**。
|
||||
|
||||
完成后,学生应该能理解:
|
||||
- 什么是 Intent
|
||||
- 什么是 State
|
||||
- 为什么页面状态不要散在一堆布尔值里
|
||||
- MVI 最小落地长什么样
|
||||
|
||||
课堂上一定要强调:
|
||||
> 第7节的 MVI 只是“最小状态管理示范”,不是整套架构革命。
|
||||
|
||||
---
|
||||
|
||||
## Step 6.1:为什么商品列表页最适合演示 MVI
|
||||
商品列表页天然就有四种很典型的状态:
|
||||
|
||||
1. `Loading`
|
||||
2. `Success`
|
||||
3. `Error`
|
||||
4. `Empty`
|
||||
|
||||
另外它还正好有几种用户动作:
|
||||
- 首次加载
|
||||
- 点击重试
|
||||
- 点击加购
|
||||
- 输入搜索词
|
||||
|
||||
所以非常适合拿来做最小 MVI 示例。
|
||||
|
||||
---
|
||||
|
||||
## Step 6.2:先定义列表页的 Intent 和 State
|
||||
|
||||
### 文件路径
|
||||
`composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt`
|
||||
|
||||
### 为什么要先定义这两个
|
||||
很多学生一上来就会直接开始改 `refreshProducts()`,
|
||||
但如果不先把:
|
||||
- Intent
|
||||
- State
|
||||
|
||||
这两个概念定义清楚,最后很容易又回到“到处散落状态变量”的写法。
|
||||
|
||||
### 建议新增的代码
|
||||
|
||||
```kotlin
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
### 课堂要点
|
||||
这里要告诉学生:
|
||||
- `Intent` 表示“用户做了什么”
|
||||
- `State` 表示“页面现在是什么状态”
|
||||
- ViewModel 的职责,就是把 Intent 处理成新的 State
|
||||
|
||||
---
|
||||
|
||||
## Step 6.3:把 `ShopUiState` 里的列表状态收口
|
||||
|
||||
### 为什么不能继续用散落字段
|
||||
之前我们在 `ShopUiState` 里有:
|
||||
- `products`
|
||||
- `loading`
|
||||
- `loadError`
|
||||
|
||||
这种写法在简单页面还能忍,
|
||||
但状态一多,很快就会出现:
|
||||
- `loading = false`
|
||||
- `loadError != null`
|
||||
- `products` 又不是空
|
||||
|
||||
这种状态组合不清晰的问题。
|
||||
|
||||
### 建议改法
|
||||
把列表状态收成一个字段:
|
||||
|
||||
```kotlin
|
||||
val productListState: ProductListState = ProductListState.Loading
|
||||
```
|
||||
|
||||
然后 `products` 仍然保留在 `ShopUiState` 里,
|
||||
这样搜索、详情、购物车数量统计都还能复用。
|
||||
|
||||
---
|
||||
|
||||
## Step 6.4:在 ViewModel 里增加 `dispatch()`
|
||||
|
||||
### 为什么这一步是 MVI 的关键
|
||||
前面只是定义了概念,
|
||||
真正让它变成最小 MVI 的,是增加一个统一入口:
|
||||
|
||||
```kotlin
|
||||
fun dispatch(intent: ProductListIntent)
|
||||
```
|
||||
|
||||
这样之后:
|
||||
- 加载
|
||||
- 重试
|
||||
- 搜索
|
||||
- 加购
|
||||
|
||||
都不再是页面零散地直接调用一堆方法,
|
||||
而是统一走 Intent。
|
||||
|
||||
### 建议写法
|
||||
|
||||
```kotlin
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 课堂说明怎么讲
|
||||
可以直接告诉学生:
|
||||
- 这里没有把 Reducer 单独拆文件
|
||||
- 但它已经具备“统一处理状态变化入口”的雏形
|
||||
- 对本节课来说,这就够了
|
||||
|
||||
---
|
||||
|
||||
## Step 6.5:重写 `refreshProducts()`,让它输出明确状态
|
||||
|
||||
### 为什么这一步要改
|
||||
因为现在 `refreshProducts()` 还是这种思路:
|
||||
- 设置 `loading = true`
|
||||
- 成功后改 `products`
|
||||
- 失败后改 `loadError`
|
||||
|
||||
这还是旧状态管理方式。
|
||||
|
||||
### 目标
|
||||
改成:
|
||||
- 先把列表置为 `Loading`
|
||||
- 请求成功后:
|
||||
- 有数据 → `Success`
|
||||
- 无数据 → `Empty`
|
||||
- 请求失败后 → `Error`
|
||||
|
||||
### 核心写法
|
||||
|
||||
```kotlin
|
||||
fun refreshProducts() {
|
||||
scope.launch {
|
||||
uiState = uiState.copy(productListState = ProductListState.Loading)
|
||||
|
||||
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 ?: "加载失败")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Step 6.6:让 `ProductListScreen` 按状态渲染
|
||||
|
||||
### 为什么 UI 层也要收口
|
||||
如果 ViewModel 已经给了:
|
||||
- `Loading`
|
||||
- `Success`
|
||||
- `Error`
|
||||
- `Empty`
|
||||
|
||||
那 UI 层就应该只关心“当前是什么状态”,
|
||||
而不是自己再重复拼判断。
|
||||
|
||||
### 推荐思路
|
||||
把原来 `ProductListScreen` 里的这几个参数:
|
||||
- `loading`
|
||||
- `error`
|
||||
- `products`
|
||||
|
||||
收成:
|
||||
|
||||
```kotlin
|
||||
state: ProductListState
|
||||
```
|
||||
|
||||
然后按 `when (state)` 渲染。
|
||||
|
||||
### 课堂要点
|
||||
这一步非常关键,因为学生会第一次明显感受到:
|
||||
**状态和 UI 是怎么一一对应起来的。**
|
||||
|
||||
---
|
||||
|
||||
## Step 6.7:搜索和加购为什么还要保留在这个页面里
|
||||
这一步学生很容易问:
|
||||
“既然都 MVI 了,为什么不把搜索结果也完全装进 `State`?”
|
||||
|
||||
课堂上建议你这样回答:
|
||||
- 可以那样做
|
||||
- 但本节课只做“最小 MVI”
|
||||
- 我们只把最核心的页面状态收口
|
||||
- 不把课堂复杂度一下拉太高
|
||||
|
||||
也就是说,这一节的重点是:
|
||||
- 学生先理解 MVI 长什么样
|
||||
- 而不是一口气把整个项目重构到最彻底
|
||||
|
||||
---
|
||||
|
||||
## Step 6.8:本步验收
|
||||
这一步做完后,学生至少应该能看到:
|
||||
|
||||
1. 列表加载时显示 `Loading`
|
||||
2. 请求失败时显示 `Error + 重试`
|
||||
3. 数据为空时显示 `Empty`
|
||||
4. 数据正常时显示 `Success`
|
||||
5. 搜索和加购还能正常工作
|
||||
|
||||
如果这一点能做到,就说明第7节里的“最小 MVI”已经落地了。
|
||||
|
||||
---
|
||||
|
||||
## Step 6.9:本步小结
|
||||
到这里,第7节其实已经完成了三件最重要的事:
|
||||
|
||||
1. **SQL 升级**
|
||||
2. **订单闭环**
|
||||
3. **最小 MVI 落地**
|
||||
|
||||
剩下最后一块,就是把错误处理再统一收一下。
|
||||
|
||||
---
|
||||
|
||||
# 十二、本节整体顺序(重新整理后的主线)
|
||||
去掉“离线优先”后,第7节建议严格按下面顺序推进:
|
||||
|
||||
1. **为什么从 Settings 升级到 SQL**
|
||||
@@ -1964,12 +2233,12 @@ private fun OrderScreen(orders: List<ShopOrder>) {
|
||||
|
||||
---
|
||||
|
||||
# 十二、下一步预告(Step 6)
|
||||
下一步开始改造商品列表页,把它收成第7节要求的最小 MVI:
|
||||
# 十三、下一步预告(Step 7)
|
||||
下一步开始把错误处理统一收口:
|
||||
|
||||
1. Intent:加载 / 重试 / 加购
|
||||
2. State:Loading / Success / Error / Empty
|
||||
3. Reducer:状态统一收敛
|
||||
1. 共享层统一 Success / Error 结构
|
||||
2. ViewModel 不再到处散落错误文案
|
||||
3. UI 层统一消费错误状态和重试动作
|
||||
|
||||
并且继续保持本节文档风格:
|
||||
- 先讲为什么
|
||||
|
||||
Reference in new issue
Block a user