Compare commits

..
22 Commits
Author SHA1 Message Date
OpenClaw 076d0efb27 docs: add lesson 7 summary and homework
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 07:29:48 +08:00
OpenClaw a0ae9eff02 docs: add koin wiring walkthrough
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 06:39:00 +08:00
OpenClaw b9933f8822 feat: add minimal koin wiring demo
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 06:30:02 +08:00
OpenClaw 0e5eff673b refactor: move lesson 7 checkout orchestration into viewmodel
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 03:55:20 +08:00
OpenClaw a773ac7867 docs: add brief MVI introduction before lesson 7 step 6
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 03:16:30 +08:00
OpenClaw 9dfe6747dd feat: add lesson 7 minimal mvi for product list
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 03:07:29 +08:00
OpenClaw e42597b8b7 feat: add lesson 7 order flow and orders screen
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 02:25:41 +08:00
OpenClaw fc8ea48ea1 fix: add explicit expect actual constructor for database factory
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 01:41:21 +08:00
OpenClaw 605b78eb50 fix: replace datetime dependency with platform time helper
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 01:36:16 +08:00
OpenClaw 5147bb7bcc build: add kotlinx-datetime for lesson 7 cart timestamps
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 00:57:49 +08:00
OpenClaw 4f32be7077 feat: migrate lesson 7 cart flow from settings to sql
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-09 00:44:57 +08:00
OpenClaw a5120b3e8a docs: add lesson 7 step 3 SQL schema walkthrough
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-08 23:54:35 +08:00
OpenClaw adb722f728 build: upgrade lesson 7 SQLDelight version to 2.2.1
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-08 22:26:06 +08:00
OpenClaw 2931909742 docs: reorganize lesson 7 scope after removing offline-first
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-08 21:05:17 +08:00
OpenClaw 54487eb829 docs: remove offline-first from lesson 7 scope
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-08 20:49:27 +08:00
OpenClaw e6f05b1b64 build: align lesson 7 SQLDelight setup with docs
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-08 13:43:38 +08:00
OpenClaw 5d3ea97f9f docs: rewrite lesson 7 as step-by-step SQLDelight guide
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-08 13:34:55 +08:00
xiaobai de2c488b8b docs: add detailed lesson 7 teaching outline
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-06 17:19:25 +08:00
xiaobai 5c32d6bdbe docs: refine lesson 7 to SQL-first with minimal MVI and offline-first flow
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-06 16:47:00 +08:00
xiaobai 837caa3058 docs: shift lesson 7 to MVI + SQL offline-first + order flow
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-06 15:44:15 +08:00
xiaobai ce062202de docs: refocus lesson 7 on architecture theory and project refactor flow
Build Android app / Build (push) Has been cancelled
Build iOS app / Build (push) Has been cancelled
Template Cleanup / Template Cleanup (push) Has been cancelled
2026-03-06 15:02:51 +08:00
xiaobai d9f2f31565 docs: expand lesson 7 KMP courseware with architecture, robustness, testing 2026-03-06 15:02:15 +08:00
26 changed files with 3841 additions and 300 deletions

No files matched your search

+4
View File
@@ -30,3 +30,7 @@ And the following Android-specific dependencies:
- [Jetpack Compose](https://developer.android.com/jetpack/compose) - [Jetpack Compose](https://developer.android.com/jetpack/compose)
- [Navigation component](https://developer.android.com/jetpack/compose/navigation) - [Navigation component](https://developer.android.com/jetpack/compose/navigation)
- [Coil](https://github.com/coil-kt/coil) for image loading - [Coil](https://github.com/coil-kt/coil) for image loading
## Local course notes
- Koin 最小注入演示:`docs/第7节补充_Koin最小注入演示.md`
@@ -50,9 +50,11 @@ 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.model.Product import com.example.minishop.model.Product
import com.example.minishop.order.ShopOrder
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
enum class Tab { Home, Cart } enum class Tab { Home, Cart, Orders }
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
@@ -60,7 +62,7 @@ fun App() {
MaterialTheme { MaterialTheme {
val snackbarHostState = remember { SnackbarHostState() } val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val vm: ShopViewModel = androidx.lifecycle.viewmodel.compose.viewModel() val vm: ShopViewModel = koinViewModel()
val ui = vm.uiState val ui = vm.uiState
Scaffold( Scaffold(
@@ -72,7 +74,8 @@ fun App() {
when { when {
ui.inDetail -> "商品详情" ui.inDetail -> "商品详情"
ui.currentTab == Tab.Home -> "KMP Mini Shopping" ui.currentTab == Tab.Home -> "KMP Mini Shopping"
else -> "购物车" ui.currentTab == Tab.Cart -> "购物车"
else -> "订单列表"
} }
) )
}, },
@@ -104,6 +107,12 @@ fun App() {
icon = { Text("🛒") }, icon = { Text("🛒") },
label = { Text("购物车(${ui.totalCount})") } label = { Text("购物车(${ui.totalCount})") }
) )
NavigationBarItem(
selected = ui.currentTab == Tab.Orders,
onClick = { vm.selectTab(Tab.Orders) },
icon = { Text("📦") },
label = { Text("订单") }
)
} }
} }
} }
@@ -119,7 +128,7 @@ fun App() {
product = vm.selectedProduct, product = vm.selectedProduct,
quantity = vm.selectedProduct?.let { vm.quantityOf(it.id) } ?: 0, quantity = vm.selectedProduct?.let { vm.quantityOf(it.id) } ?: 0,
onAdd = { onAdd = {
val msg = vm.addToCart(it.id) val msg = vm.addToCart(it)
scope.launch { scope.launch {
snackbarHostState.showSnackbar(msg) snackbarHostState.showSnackbar(msg)
} }
@@ -127,23 +136,24 @@ fun App() {
) )
ui.currentTab == Tab.Home -> ProductListScreen( ui.currentTab == Tab.Home -> ProductListScreen(
loading = ui.loading, state = ui.productListState,
error = ui.loadError,
products = vm.filteredProducts, products = vm.filteredProducts,
totalProducts = ui.products.size, totalProducts = ui.products.size,
query = ui.query, query = ui.query,
quantityOf = vm::quantityOf, quantityOf = vm::quantityOf,
onQueryChange = vm::onQueryChange, onQueryChange = vm::onQueryChange,
onRetry = vm::refreshProducts, onRetry = { vm.dispatch(ProductListIntent.Retry) },
onAdd = { onAdd = {
vm.addToCart(it.id) val msg = vm.addToCart(it)
scope.launch {
snackbarHostState.showSnackbar(msg)
}
}, },
onClick = vm::openDetail onClick = vm::openDetail
) )
else -> CartScreen( ui.currentTab == Tab.Cart -> CartScreen(
items = ui.cartItems, items = ui.cartItems,
productMap = ui.products.associateBy { it.id },
totalPrice = ui.totalPrice, totalPrice = ui.totalPrice,
onInc = vm::increase, onInc = vm::increase,
onDec = vm::decrease, onDec = vm::decrease,
@@ -156,17 +166,17 @@ fun App() {
} }
} }
) )
else -> OrderScreen(ui.orders)
} }
} }
} }
} }
} }
@Composable @Composable
private fun ProductListScreen( private fun ProductListScreen(
loading: Boolean, state: ProductListState,
error: String?,
products: List<Product>, products: List<Product>,
totalProducts: Int, totalProducts: Int,
query: String, query: String,
@@ -197,18 +207,21 @@ private fun ProductListScreen(
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
when { when (state) {
loading -> EmptyState("⏳ 加载中...") ProductListState.Loading -> EmptyState("⏳ 加载中...")
error != null -> {
is ProductListState.Error -> {
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)) { Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { 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("重试") } Button(onClick = onRetry) { Text("重试") }
} }
} }
} }
products.isEmpty() -> EmptyState("没有匹配的商品")
else -> { ProductListState.Empty -> EmptyState("没有匹配的商品")
is ProductListState.Success -> {
LazyVerticalStaggeredGrid( LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Fixed(2), columns = StaggeredGridCells.Fixed(2),
verticalItemSpacing = 10.dp, verticalItemSpacing = 10.dp,
@@ -294,7 +307,6 @@ private fun ProductDetailScreen(
@Composable @Composable
private fun CartScreen( private fun CartScreen(
items: List<CartItem>, items: List<CartItem>,
productMap: Map<String, Product>,
totalPrice: Double, totalPrice: Double,
onInc: (String) -> Unit, onInc: (String) -> Unit,
onDec: (String) -> Unit, onDec: (String) -> Unit,
@@ -315,21 +327,18 @@ private fun CartScreen(
contentPadding = PaddingValues(bottom = 96.dp) contentPadding = PaddingValues(bottom = 96.dp)
) { ) {
lazyListItems(items) { item -> lazyListItems(items) { item ->
val product = productMap[item.productId] Card(Modifier.fillMaxWidth()) {
if (product != null) { Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Card(Modifier.fillMaxWidth()) { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text(item.title, fontWeight = FontWeight.Medium)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { Text("¥${formatPrice(item.price * item.quantity)}")
Text(product.title, fontWeight = FontWeight.Medium) }
Text("¥${formatPrice(product.price * item.quantity)}") Row(verticalAlignment = Alignment.CenterVertically) {
} SmallOpButton("-") { onDec(item.productId) }
Row(verticalAlignment = Alignment.CenterVertically) { Text(" ${item.quantity} ")
SmallOpButton("-") { onDec(product.id) } SmallOpButton("+") { onInc(item.productId) }
Text(" ${item.quantity} ") Spacer(Modifier.width(8.dp))
SmallOpButton("+") { onInc(product.id) } OutlinedButton(onClick = { onRemove(item.productId) }) { Text("移除") }
Spacer(Modifier.width(8.dp))
OutlinedButton(onClick = { onRemove(product.id) }) { Text("移除") }
}
} }
} }
} }
@@ -363,6 +372,35 @@ private fun CartScreen(
} }
} }
@Composable
private fun OrderScreen(orders: List<ShopOrder>) {
if (orders.isEmpty()) {
EmptyState("还没有订单")
return
}
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
lazyListItems(orders) { order ->
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("订单号:${order.orderId}", fontWeight = FontWeight.Bold)
Text("状态:${order.status}")
Text("总价:¥${formatPrice(order.totalPrice)}")
Text("商品数:${order.items.sumOf { it.quantity }}")
order.items.forEach { item ->
Text("- ${item.title} x${item.quantity}")
}
}
}
}
}
}
@Composable @Composable
private fun ProductCover(url: String) { private fun ProductCover(url: String) {
val coverModifier = Modifier val coverModifier = Modifier
@@ -0,0 +1,21 @@
package com.example.minishop
import com.example.minishop.network.ProductApi
import com.example.minishop.repository.ProductRepository
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.GlobalContext
import org.koin.core.context.startKoin
import org.koin.dsl.module
val appModule = module {
single { ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false) }
single { ProductRepository(api = get()) }
viewModel { ShopViewModel(productRepository = get()) }
}
fun initAppKoin() {
if (GlobalContext.getOrNull() != null) return
startKoin {
modules(appModule)
}
}
@@ -3,10 +3,13 @@ package com.example.minishop
import android.os.Bundle import android.os.Bundle
import androidx.activity.ComponentActivity import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent import androidx.activity.compose.setContent
import com.example.minishop.db.initAppContext
class MainActivity : ComponentActivity() { class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
initAppContext(applicationContext)
initAppKoin()
setContent { setContent {
App() App()
} }
@@ -6,9 +6,10 @@ import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import com.example.minishop.cart.CartItem import com.example.minishop.cart.CartItem
import com.example.minishop.cart.CartRepository import com.example.minishop.cart.CartRepository
import com.example.minishop.checkout.CheckoutService import com.example.minishop.db.createShopDatabase
import com.example.minishop.model.Product import com.example.minishop.model.Product
import com.example.minishop.network.ProductApi import com.example.minishop.order.OrderRepository
import com.example.minishop.order.ShopOrder
import com.example.minishop.repository.ProductRepository import com.example.minishop.repository.ProductRepository
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -16,27 +17,41 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch 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( data class ShopUiState(
val currentTab: Tab = Tab.Home, val currentTab: Tab = Tab.Home,
val inDetail: Boolean = false, val inDetail: Boolean = false,
val selectedProductId: String? = null, val selectedProductId: String? = null,
val query: String = "", val query: String = "",
val products: List<Product> = emptyList(), val products: List<Product> = emptyList(),
val loading: Boolean = false, val productListState: ProductListState = ProductListState.Loading,
val loadError: String? = null,
val cartItems: List<CartItem> = emptyList(), val cartItems: List<CartItem> = emptyList(),
val totalCount: Int = 0, val totalCount: Int = 0,
val totalPrice: Double = 0.0 val totalPrice: Double = 0.0,
val orders: List<ShopOrder> = emptyList()
) )
class ShopViewModel : ViewModel() { class ShopViewModel(
private val productRepository: ProductRepository,
) : ViewModel() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private val productRepository = ProductRepository( private val database = createShopDatabase()
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false) private val cartRepository = CartRepository(database)
) private val orderRepository = OrderRepository(database)
private val cartRepository = CartRepository()
private val checkoutService = CheckoutService(cartRepository)
var uiState by mutableStateOf(ShopUiState()) var uiState by mutableStateOf(ShopUiState())
private set private set
@@ -58,24 +73,53 @@ class ShopViewModel : ViewModel() {
get() = uiState.products.firstOrNull { it.id == uiState.selectedProductId } get() = uiState.products.firstOrNull { it.id == uiState.selectedProductId }
init { init {
refreshProducts() dispatch(ProductListIntent.Load)
syncCart() 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() { fun refreshProducts() {
scope.launch { scope.launch {
uiState = uiState.copy(loading = true, loadError = null) uiState = uiState.copy(productListState = ProductListState.Loading)
val list = runCatching { productRepository.getProducts() }
.onFailure { uiState = uiState.copy(loadError = it.message ?: "加载失败") }
.getOrDefault(emptyList())
uiState = uiState.copy(products = list, loading = false) runCatching { productRepository.getProducts() }
syncCart() .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) { fun onQueryChange(value: String) {
uiState = uiState.copy(query = value) dispatch(ProductListIntent.Search(value))
} }
fun selectTab(tab: Tab) { fun selectTab(tab: Tab) {
@@ -93,9 +137,8 @@ class ShopViewModel : ViewModel() {
fun quantityOf(productId: String): Int = fun quantityOf(productId: String): Int =
uiState.cartItems.firstOrNull { it.productId == productId }?.quantity ?: 0 uiState.cartItems.firstOrNull { it.productId == productId }?.quantity ?: 0
fun addToCart(productId: String): String { fun addToCart(product: Product): String {
cartRepository.add(productId) dispatch(ProductListIntent.AddToCart(product))
syncCart()
return "已加入购物车" return "已加入购物车"
} }
@@ -120,22 +163,34 @@ class ShopViewModel : ViewModel() {
} }
fun checkout(): String { fun checkout(): String {
val productMap = uiState.products.associateBy { it.id } val cartItems = cartRepository.items()
val result = checkoutService.checkout(productMap) if (cartItems.isEmpty()) {
return "购物车为空"
}
val order = orderRepository.createOrder(cartItems)
?: return "创建订单失败"
cartRepository.clear()
syncCart() syncCart()
return result.message syncOrders()
uiState = uiState.copy(currentTab = Tab.Orders)
return "下单成功,订单号:${order.orderId}"
} }
private fun syncCart() { private fun syncCart() {
val items = cartRepository.items() val items = cartRepository.items()
val productMap = uiState.products.associateBy { it.id }
uiState = uiState.copy( uiState = uiState.copy(
cartItems = items, cartItems = items,
totalCount = items.sumOf { it.quantity }, totalCount = items.sumOf { it.quantity },
totalPrice = checkoutService.totalPrice(productMap) totalPrice = items.sumOf { it.price * it.quantity }
) )
} }
private fun syncOrders() {
uiState = uiState.copy(orders = orderRepository.getOrders())
}
override fun onCleared() { override fun onCleared() {
scope.cancel() scope.cancel()
super.onCleared() super.onCleared()
+71 -34
View File
@@ -1,48 +1,85 @@
[图片] # 第6-7节课程大纲|KMP 商城:网络存储与数据层升级
第6节:KMP 商城实战——网络与存储
对应 SkillMap: ## 第6节:KMP 商城实战——网络与存储
**对应 SkillMap:**
5. 跨平台技术栈(Ktor / Settings / Serialization) 5. 跨平台技术栈(Ktor / Settings / Serialization)
本节目标
### 本节目标
- 在 KMP 共享层完成网络请求与本地存储能力 - 在 KMP 共享层完成网络请求与本地存储能力
- 完成商城最小闭环:商品列表(网络)+ 购物车(存储) - 完成商城最小闭环:商品列表(网络)+ 购物车(存储)
- Android 端只做展示与交互,不承载核心业务逻辑 - Android 端只做展示与交互,不承载核心业务逻辑
本节内容
### 本节内容(1~2小时)
1. KMP 中集成 Ktor 网络 1. KMP 中集成 Ktor 网络
2. 封装通用网络请求能力 2. 封装通用网络请求能力
3. 商品列表接口实战(可先 Mock 后真实) 3. 商品列表接口实战(可先 Mock 后真实)
4. 集成跨平台存储(Multiplatform Settings) 4. 集成跨平台存储(Multiplatform Settings)
5. 购物车数据本地持久化 5. 购物车数据本地持久化
6. 数据解析(kotlinx-serialization) 6. 数据解析(kotlinx-serialization)
课堂实战产出
### 课堂实战产出
- 共享层实现:商品列表拉取 + 购物车持久化 - 共享层实现:商品列表拉取 + 购物车持久化
- Android 页面可运行:商品列表展示、加购、重启后数据不丢失 - Android 页面可运行:商品展示、加购、重启后数据不丢失
课后作业
- 完成商品详情页面 ### 课后作业(≤2小时)
- 购物车操作(删除条目 / 数量修改+- / 清空) - 完成商品详情接口
- 提交运行录屏 - 存储优化:删除 / 数量修改
- 提交运行截图 + 核心代码截图
--- ---
第7节:KMP 商城实战——架构封装与业务整合
对应 SkillMap: ## 第7节:KMP 商城实战——SQL 升级 + 最小架构改造
**对应 SkillMap:**
4. KMP 核心能力 + 6. 平台集成能力 + 7. 工程化与业务落地 4. KMP 核心能力 + 6. 平台集成能力 + 7. 工程化与业务落地
本节目标
- 将第6节功能重构为标准可维护架构 ### 本节定位
- 建立共享层分层规范与职责边界 第7节重点不是“大量架构理论”,而是把项目升级到更接近真实业务:
- 完成可演示、可复用的商城项目结构 - 数据层从 Settings 升级到 SQL(结构化存储)
本节内容 - 补齐订单最小业务闭环
1. KMP 项目分层设计 - MVI 只做最小化落地(1个核心页面)
2. 纯逻辑层规范写法
3. 通用 Repository 封装 ### 本节目标
4. KMP 与 Android 架构最佳实践 - 完成第6节作业复盘并确定改造点
5. 常见问题与避坑 - 将购物车存储从 Settings 升级到 SQL
课堂实战产出 - 完成订单最小闭环(下单后清空购物车 + 订单列表)
- 将第6节商城重构为标准架构 - 在一个核心页面落地最小 MVI(Intent / State / Reducer)
- 完成可复用、可维护的 KMP 模块 - 统一错误呈现,减少异常处理分散
- 完整商城流程演示通过
结业作业 ### 本节内容(1~2小时)
结算流程补齐(共享层实现) 1. **第6节作业讲解与问题归类**
- 新增结算方法(模拟成功/失败) - 高频问题:网络异常、解析失败、存储一致性
- 结算成功后清空购物车并给出提示 - 从“能跑”对齐到“可维护”
- 网络加载失败时显示错误态
- 提供“重试”按钮并可恢复 2. **数据层升级:Settings → SQL(核心)**
提交运行录屏 - 为什么要升级:查询、排序、扩展能力
- 购物车表、订单表、订单明细表最小字段设计
- Repository 改造:统一读写本地库
3. **订单最小闭环(核心)**
- 从购物车生成订单(简化版)
- 下单成功后清空购物车
- 订单列表页展示本地下单记录
4. **MVI 最小化落地(补充)**
- 仅改造一个核心页面(建议商品列表页)
- Intent:加载/重试/加购
- State:Loading / Success / Error / Empty
- Reducer:状态统一收敛
5. **统一错误呈现(补充)**
- 共享层统一错误结构(Success / Error)
- UI 层仅消费标准错误,避免异常处理分散
- 统一重试入口与错误提示文案
### 课堂实战产出
- 完成购物车与订单的 SQL 本地持久化
- 完成“购物车→下单→订单列表”闭环演示
- 完成 1 个核心页面的最小 MVI 改造
- 完成统一错误呈现的基础收口
### 课后作业(≤2小时)
- 增加订单状态字段并支持筛选(全部/待支付/已完成)
- 增加手动刷新与重试入口,完善错误提示
- 提交运行录屏(包含加购、下单、订单列表展示)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,634 @@
# 第7节补充|Koin 最小注入演示
## 主题:只用一小段依赖注入,演示 Koin 怎么接进现有项目
> 这一份补充文档不追求“全项目都改成依赖注入”,
> 只演示最小可理解的一段:
>
> `ProductApi -> ProductRepository -> ShopViewModel`
>
> 这样做的目的不是大重构,
> 而是让学生先看懂:
> 1. Koin 是干什么的
> 2. 在 KMP / Compose Android 项目里怎么引用
> 3. 怎么把“手动 new 对象”改成“由容器提供对象”
---
# 一、先讲清楚:Koin 是什么
## 1. Koin 是干什么的
Koin 是一个 Kotlin 生态里很常见的**依赖注入(Dependency Injection, DI)**库。
它解决的核心问题是:
> **对象不要在业务类里到处自己 new,
> 而是统一交给一个容器来创建和提供。**
比如以前我们可能在 `ShopViewModel` 里直接写:
```kotlin
private val productRepository = ProductRepository(
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
)
```
这种写法的缺点是:
- ViewModel 自己决定依赖怎么创建
- 以后如果 `ProductApi` 参数变了,要改 ViewModel
- 如果以后想替换 mock / test 实现,也不方便
- 对象创建逻辑散落在业务代码里
Koin 的思路是:
- 把对象创建逻辑集中写在 `module` 里
- 业务类只声明“我需要什么”
- 容器负责把对象注入进来
---
## 2. 什么叫“依赖注入”
比如 `ShopViewModel` 需要 `ProductRepository`,
那 `ProductRepository` 就是它的一个**依赖**。
如果我们把它写成:
```kotlin
class ShopViewModel(
private val productRepository: ProductRepository,
) : ViewModel()
```
这就叫**构造函数注入**。
意思是:
- `ShopViewModel` 不再自己创建 `ProductRepository`
- 谁来创建?由外部容器(这里就是 Koin)提供
这是依赖注入里最常见、也最推荐的方式。
---
## 3. 为什么这里只做“最小演示”
这次不打算把整个项目都改成 Koin,原因很简单:
1. 课堂演示不需要一步到位
2. 学生第一次接触 DI,先理解一条链路最重要
3. 先演示成功,再决定要不要扩到数据库、购物车、订单
所以本补充文档只改这一段:
- `ProductApi`
- `ProductRepository`
- `ShopViewModel`
- Compose 页面如何从 Koin 拿 ViewModel
购物车 / 订单 / SQLDelight 先继续保持原写法,不强行一起改。
---
# 二、这个项目里怎么引用 Koin
## 1. Gradle 里已经有哪些 Koin 依赖
当前项目里已经有这两类依赖:
### `shared/build.gradle.kts`
```kotlin
commonMain.dependencies {
implementation(libs.koin.core)
}
```
这里的 `koin-core` 是 Koin 的核心能力,
适合放在共享层或纯 Kotlin 层使用。
### `composeApp/build.gradle.kts`
```kotlin
androidMain.dependencies {
implementation(libs.koin.androidx.compose)
}
```
这里的 `koin-androidx-compose` 是给 Android + Compose 场景用的,
主要用于:
- 在 Compose 中获取依赖
- 在 Compose 中获取由 Koin 管理的 ViewModel
---
## 2. `libs.versions.toml` 里是怎么声明的
文件路径:`gradle/libs.versions.toml`
当前项目里对应的是:
```toml
[versions]
koin = "4.1.0"
[libraries]
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
koin-androidx-compose = { module = "io.insert-koin:koin-androidx-compose", version.ref = "koin" }
```
这说明项目已经把 Koin 版本统一收在版本目录里了。
---
## 3. “如何引用”分成两层理解
很多同学会把“引用”只理解成 `implementation(...)`,
其实这里有两层:
### 第一层:Gradle 依赖引用
也就是在构建脚本里写:
```kotlin
implementation(libs.koin.core)
implementation(libs.koin.androidx.compose)
```
### 第二层:代码中的 API 引用
也就是在 Kotlin 代码里 import 并使用,比如:
```kotlin
import org.koin.androidx.compose.koinViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
```
课堂上建议把这两层都讲清楚,
不然学生会以为“加了依赖就等于接入完成”。
---
# 三、这次最小演示要改什么
本次实际落地只改 4 个点:
1. 新增一个 `AppModule.kt`
2. 在 `MainActivity` 启动 Koin
3. 在 `App.kt` 里改成 `koinViewModel()`
4. 把 `ShopViewModel` 改成构造函数注入 `ProductRepository`
这就是完整演示闭环。
---
# 四、Step 1:新增 Koin module
## 为什么要先建 module
Koin 不是自动凭空知道要创建什么对象的。
我们需要先告诉它:
- `ProductApi` 怎么创建
- `ProductRepository` 怎么创建
- `ShopViewModel` 怎么创建
这个“告诉它如何创建对象”的地方,就叫 `module`。
## 新增文件
文件路径:
`composeApp/src/androidMain/kotlin/com/example/minishop/AppModule.kt`
完整代码:
```kotlin
package com.example.minishop
import com.example.minishop.network.ProductApi
import com.example.minishop.repository.ProductRepository
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.GlobalContext
import org.koin.core.context.startKoin
import org.koin.dsl.module
val appModule = module {
single { ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false) }
single { ProductRepository(api = get()) }
viewModel { ShopViewModel(productRepository = get()) }
}
fun initAppKoin() {
if (GlobalContext.getOrNull() != null) return
startKoin {
modules(appModule)
}
}
```
---
## 这一段怎么讲
### 1)`module { ... }` 是干什么的
它表示:
> 这里统一描述“哪些对象由 Koin 管理,以及它们怎么创建”。
### 2)`single { ... }` 是什么意思
`single` 表示单例。
也就是整个容器里,这个对象只创建一份,后面重复使用。
这里:
```kotlin
single { ProductApi(...) }
single { ProductRepository(api = get()) }
```
表示:
- `ProductApi` 只创建一份
- `ProductRepository` 只创建一份
### 3)`get()` 是什么意思
`get()` 的意思是:
> 从 Koin 容器里拿一个当前需要的依赖。
比如:
```kotlin
single { ProductRepository(api = get()) }
```
表示:
- 创建 `ProductRepository` 时,`api` 参数不手动 new
- 而是从容器里取一个 `ProductApi`
### 4)`viewModel { ... }` 是什么意思
```kotlin
viewModel { ShopViewModel(productRepository = get()) }
```
这表示:
- `ShopViewModel` 由 Koin 按 ViewModel 的方式来管理
- 构造它时需要一个 `ProductRepository`
- 这个依赖同样从容器里获取
### 5)为什么要有 `initAppKoin()`
因为定义了 module 还不够,
还需要在 App 启动时真正把 Koin 启起来。
`initAppKoin()` 就是在做这件事。
### 6)为什么要判断 `GlobalContext.getOrNull()`
这是为了避免重复初始化。
如果 Activity 重建或某些场景下再次触发初始化,
直接 `startKoin()` 可能会报错。
所以先判断:
- 如果已经启动过,就直接返回
- 没启动过,才执行 `startKoin()`
---
# 五、Step 2:在 MainActivity 启动 Koin
## 为什么要在入口启动
Koin 只是“定义好了规则”还不够,
还要在应用入口把容器真正启动起来。
在这个项目里,最直接的入口就是 `MainActivity`。
## 修改文件
文件路径:
`composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt`
修改后代码:
```kotlin
package com.example.minishop
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.example.minishop.db.initAppContext
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initAppContext(applicationContext)
initAppKoin()
setContent {
App()
}
}
}
```
---
## 这一段怎么讲
这里要让学生知道:
1. `initAppContext(applicationContext)`
- 这是原来数据库那套逻辑需要的
- 和 Koin 是两回事
2. `initAppKoin()`
- 这是本次新增
- 作用是启动 Koin 容器
顺序上通常就是:
- 先做原有基础初始化
- 再启动 Koin
- 最后再进入 Compose UI
---
# 六、Step 3:在 Compose 页面里从 Koin 拿 ViewModel
## 原来是怎么写的
原来在 `App.kt` 里是这样:
```kotlin
val vm: ShopViewModel = androidx.lifecycle.viewmodel.compose.viewModel()
```
这表示使用默认方式获取 ViewModel。
## 现在改成什么
我们改成:
```kotlin
import org.koin.androidx.compose.koinViewModel
val vm: ShopViewModel = koinViewModel()
```
## 修改文件
文件路径:
`composeApp/src/androidMain/kotlin/com/example/minishop/App.kt`
关键改动:
```kotlin
import org.koin.androidx.compose.koinViewModel
```
以及:
```kotlin
val vm: ShopViewModel = koinViewModel()
```
---
## 这一段怎么讲
### 1)`koinViewModel()` 是干什么的
它的作用是:
> 在 Compose 里,向 Koin 要一个 ViewModel。
也就是说,页面不再自己决定怎么创建 ViewModel,
而是交给 Koin 按我们在 module 里写好的规则来创建。
### 2)这就是“代码中如何引用”的一个典型例子
除了 Gradle 里的依赖引用,
这里也要让学生看到:
```kotlin
import org.koin.androidx.compose.koinViewModel
```
这是 Koin 在代码中的实际用法引用。
### 3)为什么这里不直接写 `ShopViewModel()`
因为如果你直接在 UI 里 new:
- 又绕回手动创建对象了
- DI 就失去意义了
用了 `koinViewModel()` 后,UI 只负责声明“我要这个 ViewModel”,
不再负责“怎么造出来”。
---
# 七、Step 4:把 ShopViewModel 改成构造函数注入
## 原来是怎么写的
原来的写法是:
```kotlin
class ShopViewModel : ViewModel() {
private val productRepository = ProductRepository(
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
)
...
}
```
这种写法的问题在于:
- `ShopViewModel` 自己 new 了依赖
- 依赖创建逻辑和业务逻辑混在一起
## 现在改成什么
改成:
```kotlin
class ShopViewModel(
private val productRepository: ProductRepository,
) : ViewModel()
```
## 修改文件
文件路径:
`composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt`
关键改动如下:
```kotlin
class ShopViewModel(
private val productRepository: ProductRepository,
) : ViewModel() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private val database = createShopDatabase()
private val cartRepository = CartRepository(database)
private val orderRepository = OrderRepository(database)
...
}
```
---
## 这一段怎么讲
### 1)这就是构造函数注入
意思是:
- `ShopViewModel` 不自己 new `ProductRepository`
- 由外部把 `ProductRepository` 传进来
而这个“外部”,在这里就是 Koin。
### 2)为什么只注入 `ProductRepository`
因为这次我们只想做一个**最小演示切片**。
如果把:
- `CartRepository`
- `OrderRepository`
- `ShopDatabase`
- `DatabaseFactory`
全都一口气改成注入,
课堂复杂度会一下升高。
所以这次刻意只改一小段:
- 先让学生看懂依赖注入的基本形状
- 不急着把所有对象都交给容器
### 3)这不是“最佳最终形态”,而是“教学上最合适的第一步”
要明确告诉学生:
> 现在这版不是要证明“项目已经完整 DI 化”,
> 而是先证明“我们已经会把一条依赖链接入 Koin”。
---
# 八、改造前后对比
## 改造前
```kotlin
class ShopViewModel : ViewModel() {
private val productRepository = ProductRepository(
api = ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false)
)
}
```
特点:
- ViewModel 自己创建依赖
- 创建逻辑写死在类内部
- 不利于替换和测试
## 改造后
```kotlin
class ShopViewModel(
private val productRepository: ProductRepository,
) : ViewModel()
```
配合:
```kotlin
val appModule = module {
single { ProductApi(baseUrl = "http://10.0.2.2:8080", useMock = false) }
single { ProductRepository(api = get()) }
viewModel { ShopViewModel(productRepository = get()) }
}
```
特点:
- ViewModel 只声明依赖,不负责创建
- 对象创建逻辑集中在 module
- UI 通过 `koinViewModel()` 获取 ViewModel
---
# 九、这次改动的完整链路图
可以直接把这段讲给学生:
```text
MainActivity
-> initAppKoin()
-> startKoin(modules(appModule))
appModule
-> single ProductApi
-> single ProductRepository(api = ProductApi)
-> viewModel ShopViewModel(productRepository = ProductRepository)
App.kt
-> koinViewModel<ShopViewModel>()
ShopViewModel
-> 直接使用注入进来的 ProductRepository
```
如果学生能看懂这张链路图,
就说明这次最小 Koin 演示已经讲明白了。
---
# 十、课堂里一定要强调的几个点
## 1. Koin 不是“把所有类都塞进去”
不要让学生误解成:
- 只要用了 Koin,项目里所有对象都必须注入
不是的。
正确理解是:
- 先从最适合的对象开始
- 逐步收口对象创建逻辑
- 一次改一条链路最稳
## 2. 最适合先注入的通常是这些对象
- API Client
- Repository
- ViewModel
- Service / UseCase
## 3. 纯工具类 / 纯函数不一定要硬塞进 Koin
如果一个类没有状态、没有复杂构造、也没必要复用,
那不一定非要用 DI。
## 4. 这次只是“演示注入”,不是“大改架构”
这点一定要说清楚。
不然学生会以为接 Koin 就要把项目推倒重来。
---
# 十一、如何继续扩展
如果后面想把这个项目继续往完整 DI 推,可以按这个顺序扩:
1. 注入 `ShopDatabase`
2. 注入 `CartRepository`
3. 注入 `OrderRepository`
4. 再把 `DatabaseFactory` / 平台依赖也收口
也就是说,后续可以从:
```text
ProductApi -> ProductRepository -> ShopViewModel
```
继续扩成:
```text
ShopDatabase -> CartRepository -> OrderRepository -> ShopViewModel
```
但这已经超出这次“最小演示”的范围了。
---
# 十二、本次最小演示的验收标准
做到下面这几点,就说明这次 Koin 接入已经成立:
- [ ] 项目里新增了 `AppModule.kt`
- [ ] `MainActivity` 启动了 `initAppKoin()`
- [ ] `App.kt` 已经从 `viewModel()` 改成 `koinViewModel()`
- [ ] `ShopViewModel` 已经通过构造函数接收 `ProductRepository`
- [ ] `ProductApi` 和 `ProductRepository` 的创建逻辑已经移出 `ShopViewModel`
---
# 十三、本节小结
这次补充文档想讲清楚的,不是“如何把项目彻底重构成 DI 架构”,
而是先让学生真正理解下面这句话:
> Koin 的核心价值,不是语法本身,
> 而是把对象创建逻辑从业务代码里拿出来,集中管理。
而在这个项目里,我们已经通过最小一段改造演示了这件事:
- `ProductApi` 不再在 ViewModel 里手动 new
- `ProductRepository` 不再在 ViewModel 里手动 new
- `ShopViewModel` 通过构造函数声明依赖
- Compose 页面通过 `koinViewModel()` 获取 ViewModel
这就是一个完整、可讲、也足够轻量的 Koin 入门示例。
+266
View File
@@ -0,0 +1,266 @@
# 第7节详细授课大纲
## 主题:SQL 数据层升级 + 订单闭环 + 最小 MVI 落地
## 一、课程定位
这一节不是继续堆功能,而是把第6节的商城项目做一次更接近真实业务的升级:
- 购物车存储:Settings → SQL
- 业务闭环:补齐下单 → 订单列表
- 页面状态:增加一个最小 MVI 示例
- 错误处理:从分散 try-catch 收到统一错误结构
---
## 二、教学目标
学生完成本节后,应该能理解并完成:
1. 为什么 Settings 不适合继续承载复杂业务数据
2. SQL 在 KMP 项目里的作用是什么
3. 如何把购物车从 Settings 升级到 SQL
4. 最小 MVI 在 Compose 页面里如何落地
5. 如何完成“购物车 → 下单 → 订单列表”的最小闭环
6. 为什么错误呈现要统一收口
---
## 三、整体时间分配
如果按 90 分钟左右来设计,可以这样分:
### 1. 第6节作业复盘:10 分钟
### 2. 为什么从 Settings 升级到 SQL:10 分钟
### 3. SQL 数据表设计与 Repository 改造:25 分钟
### 4. 订单闭环实现:15 分钟
### 5. 最小 MVI 落地:15 分钟
### 6. 统一错误呈现:10 分钟
### 7. 总结与课后作业:5 分钟
---
# 四、详细授课结构
## 模块1:第6节作业复盘
### 目标
承接上一节,顺势引出第7节为什么要升级数据层。
### 要讲的内容
1. 第6节已经完成了什么
- 商品列表网络请求
- 购物车本地持久化
- 基础业务闭环已经可运行
2. 当前实现的问题
- Settings 本质是 key-value
- 当业务需要查询、排序、记录历史时会越来越难维护
- 当前购物车能存,但不适合扩展成订单体系
3. 引出第7节核心问题
- 如果要继续做订单和历史记录
- 现有存储方案就不够用了
### 输出结论
> 第7节不是简单加页面,而是升级项目的数据层能力,并补齐真正的业务闭环。
---
## 模块2:为什么要从 Settings 升级到 SQL
### 目标
让学生明确:SQL 不是为了“更高级”,而是为了“更适合当前业务”。
### 要讲的内容
### 2.1 Settings 适合什么
- 保存简单配置
- 登录态、开关、轻量缓存
- 小规模 key-value 数据
### 2.2 SQL 适合什么
- 多条结构化数据
- 增删改查
- 排序、筛选、统计
- 多业务对象管理
### 2.3 在当前商城项目里的对应场景
- 购物车:适合放 SQL
- 订单:更适合放 SQL
- 后续收藏、地址、历史记录也都更适合 SQL
- 商品列表本节仍保持网络请求,不强行扩展为缓存体系
### 这一部分建议落到一句话
> Settings 解决“存一个值”,SQL 解决“管理一组业务数据”。
---
## 模块3:SQL 数据表设计 + Repository 改造
### 目标
让学生知道,第7节到底要建哪些表,并理解为什么 Repository 仍然是统一数据入口。
### 要讲的内容
### 3.1 购物车表设计
建议字段:
- productId
- title
- price
- imageUrl
- quantity
- updatedAt
### 3.2 订单表设计
建议字段:
- orderId
- totalPrice
- createdAt
- status
### 3.3 订单明细表设计
建议字段:
- id
- orderId
- productId
- title
- price
- imageUrl
- quantity
### 3.4 Repository 改造重点
- CartRepository:从 Settings 改成 SQL
- OrderRepository:新增创建订单 / 查询订单能力
- UI 不关心底层是 Settings 还是 SQL
- Repository 负责屏蔽实现细节
### 这一部分建议给学生的认识
> 真正可维护的项目,不是页面直接连存储,而是页面只依赖统一的数据入口。
---
## 模块4:订单最小闭环
### 目标
让第7节有完整成果,而不是只停留在“换了个存储方式”。
### 要讲的内容
### 4.1 闭环流程
- 商品加入购物车
- 进入购物车页
- 点击提交订单
- 创建订单记录
- 清空购物车
- 打开订单列表页查看结果
### 4.2 这部分为什么重要
- 证明 SQL 升级不是空转
- 让学生看到结构化数据的业务价值
- 为后续扩展订单状态、历史记录打基础
### 4.3 本节只做最小版
不用讲:
- 支付流程
- 优惠券
- 复杂订单状态流转
只要把下单闭环打通就够。
---
## 模块5:最小 MVI 落地
### 目标
只让学生理解一个页面的状态管理,不把 MVI 讲成整套沉重架构课。
### 要讲的内容
### 5.1 为什么这里引入 MVI
不是因为 KMP 必须用 MVI,
而是因为 Compose 页面非常适合用“单一状态源”管理界面。
### 5.2 只讲三个核心概念
#### Intent
用户动作:
- LoadProducts
- Retry
- AddToCart
#### State
页面状态:
- Loading
- Success
- Error
- Empty
#### Reducer
收到动作后,如何生成新的状态
### 5.3 为什么只改一个页面
- 让学生理解方法,而不是淹死在重构细节里
- 商品列表页最适合演示状态变化
### 这一部分结论
> MVI 在本节只是“状态管理示范”,不是主角。
---
## 模块6:统一错误呈现
### 目标
让学生理解:代码不是能跑就够,错误处理也要有统一入口。
### 要讲的内容
- 为什么不能每层都各自 try-catch、各自拼文案
- 共享层统一 Success / Error 结构的好处
- UI 层只消费标准错误对象
- 重试按钮和错误提示应该统一出口
### 这一部分建议落到一句话
> 错误处理如果到处散落,项目会越来越难维护;统一结构是工程化的起点之一。
---
## 模块7:本节总结
### 目标
帮助学生把第7节的核心收束成几个关键词。
### 总结要点
本节做了四件事:
1. **数据层升级**
- Settings 不再承担复杂业务数据
- 购物车和订单交给 SQL
2. **业务闭环补齐**
- 从购物车生成订单
- 下单后清空购物车
- 订单列表可查看结果
3. **状态管理升级**
- 用最小 MVI 管理一个核心页面
- 让状态变化更清晰
4. **错误处理收口**
- 共享层统一错误结构
- UI 层只负责呈现和重试
---
## 五、本节最终产出
学生本节下课时,至少要有:
- SQL 版购物车
- SQL 版订单记录
- 一个页面完成最小 MVI 改造
- 下单后可在订单列表看到结果
- 错误展示和重试入口有统一收口
---
## 六、课后作业
建议只留 2~3 个,不要太散:
1. 给订单增加状态字段
- 例如:待支付 / 已完成
2. 增加订单筛选
- 全部 / 待支付 / 已完成
3. 提交运行录屏
- 包含加购
- 包含下单生成订单
- 包含订单列表展示
+4
View File
@@ -14,6 +14,7 @@ kotlinx-serialization = "1.8.1"
ksp = "2.2.0-2.0.2" ksp = "2.2.0-2.0.2"
ktor = "3.1.3" ktor = "3.1.3"
multiplatform-settings = "1.1.1" multiplatform-settings = "1.1.1"
sqldelight = "2.2.1"
[libraries] [libraries]
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" }
@@ -33,6 +34,8 @@ ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "kto
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" } ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" } ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
multiplatform-settings-no-arg = { module = "com.russhwolf:multiplatform-settings-no-arg", version.ref = "multiplatform-settings" } multiplatform-settings-no-arg = { module = "com.russhwolf:multiplatform-settings-no-arg", version.ref = "multiplatform-settings" }
sqldelight-android-driver = { module = "app.cash.sqldelight:android-driver", version.ref = "sqldelight" }
sqldelight-native-driver = { module = "app.cash.sqldelight:native-driver", version.ref = "sqldelight" }
[plugins] [plugins]
androidApplication = { id = "com.android.application", version.ref = "agp" } androidApplication = { id = "com.android.application", version.ref = "agp" }
@@ -43,3 +46,4 @@ kmpNativeCoroutines = { id = "com.rickclephas.kmp.nativecoroutines", version.ref
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" }
+11
View File
@@ -7,6 +7,7 @@ plugins {
alias(libs.plugins.kotlinxSerialization) alias(libs.plugins.kotlinxSerialization)
alias(libs.plugins.ksp) alias(libs.plugins.ksp)
alias(libs.plugins.kmpNativeCoroutines) alias(libs.plugins.kmpNativeCoroutines)
alias(libs.plugins.sqldelight)
} }
kotlin { kotlin {
@@ -31,9 +32,11 @@ kotlin {
sourceSets { sourceSets {
androidMain.dependencies { androidMain.dependencies {
implementation(libs.ktor.client.okhttp) implementation(libs.ktor.client.okhttp)
implementation(libs.sqldelight.android.driver)
} }
iosMain.dependencies { iosMain.dependencies {
implementation(libs.ktor.client.darwin) implementation(libs.ktor.client.darwin)
implementation(libs.sqldelight.native.driver)
} }
commonMain.dependencies { commonMain.dependencies {
implementation(libs.ktor.client.core) implementation(libs.ktor.client.core)
@@ -52,6 +55,14 @@ kotlin {
} }
} }
sqldelight {
databases {
create("ShopDatabase") {
packageName.set("com.example.minishop.db")
}
}
}
android { android {
namespace = "com.example.minishop.shared" namespace = "com.example.minishop.shared"
compileSdk = 35 compileSdk = 35
@@ -0,0 +1,10 @@
package com.example.minishop.db
import android.content.Context
lateinit var appContext: Context
private set
fun initAppContext(context: Context) {
appContext = context.applicationContext
}
@@ -0,0 +1,10 @@
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
actual class DatabaseFactory actual constructor() {
actual fun createDriver(): SqlDriver {
return AndroidSqliteDriver(ShopDatabase.Schema, appContext, "shop.db")
}
}
@@ -0,0 +1,3 @@
package com.example.minishop.platform
actual fun currentTimeMillis(): Long = System.currentTimeMillis()
@@ -1,9 +1,9 @@
package com.example.minishop.cart package com.example.minishop.cart
import kotlinx.serialization.Serializable
@Serializable
data class CartItem( data class CartItem(
val productId: String, val productId: String,
val quantity: Int val quantity: Int,
val title: String,
val price: Double,
val imageUrl: String
) )
@@ -1,41 +1,79 @@
package com.example.minishop.cart package com.example.minishop.cart
import com.example.minishop.db.ShopDatabase
import com.example.minishop.model.Product
import com.example.minishop.platform.currentTimeMillis
class CartRepository( class CartRepository(
private val storage: CartStorage = CartStorage() private val database: ShopDatabase
) { ) {
private val map = storage.load().associateBy { it.productId }.toMutableMap() private val queries = database.cartQueries
fun items(): List<CartItem> = map.values.sortedBy { it.productId } fun items(): List<CartItem> {
return queries.selectAll().executeAsList().map {
CartItem(
productId = it.product_id,
quantity = it.quantity.toInt(),
title = it.title,
price = it.price,
imageUrl = it.image_url
)
}
}
fun add(productId: String) { fun add(product: Product) {
val old = map[productId] val current = queries.selectById(product.id).executeAsOneOrNull()
map[productId] = if (old == null) CartItem(productId, 1) else old.copy(quantity = old.quantity + 1) val nextQuantity = (current?.quantity?.toInt() ?: 0) + 1
persist() upsert(product, nextQuantity)
} }
fun increase(productId: String) { fun increase(productId: String) {
val old = map[productId] ?: return val current = queries.selectById(productId).executeAsOneOrNull() ?: return
map[productId] = old.copy(quantity = old.quantity + 1) queries.insertOrReplace(
persist() product_id = current.product_id,
title = current.title,
price = current.price,
image_url = current.image_url,
quantity = current.quantity + 1,
updated_at = nowMillis()
)
} }
fun decrease(productId: String) { fun decrease(productId: String) {
val old = map[productId] ?: return val current = queries.selectById(productId).executeAsOneOrNull() ?: return
if (old.quantity <= 1) map.remove(productId) else map[productId] = old.copy(quantity = old.quantity - 1) val next = current.quantity.toInt() - 1
persist() if (next <= 0) {
queries.deleteById(productId)
} else {
queries.insertOrReplace(
product_id = current.product_id,
title = current.title,
price = current.price,
image_url = current.image_url,
quantity = next.toLong(),
updated_at = nowMillis()
)
}
} }
fun remove(productId: String) { fun remove(productId: String) {
map.remove(productId) queries.deleteById(productId)
persist()
} }
fun clear() { fun clear() {
map.clear() queries.deleteAll()
persist()
} }
private fun persist() { private fun upsert(product: Product, quantity: Int) {
storage.save(items()) queries.insertOrReplace(
product_id = product.id,
title = product.title,
price = product.price,
image_url = product.imageUrl,
quantity = quantity.toLong(),
updated_at = nowMillis()
)
} }
private fun nowMillis(): Long = currentTimeMillis()
} }
@@ -1,21 +1,4 @@
package com.example.minishop.cart package com.example.minishop.cart
import com.russhwolf.settings.Settings @Deprecated("Lesson 7 switched cart persistence from Settings to SQLDelight")
import kotlinx.serialization.encodeToString class CartStorage
import kotlinx.serialization.json.Json
class CartStorage(
private val settings: Settings = Settings(),
private val json: Json = Json { ignoreUnknownKeys = true }
) {
private val key = "cart_items"
fun load(): List<CartItem> {
val raw = settings.getStringOrNull(key) ?: return emptyList()
return runCatching { json.decodeFromString<List<CartItem>>(raw) }.getOrElse { emptyList() }
}
fun save(items: List<CartItem>) {
settings.putString(key, json.encodeToString(items))
}
}
@@ -1,34 +1,4 @@
package com.example.minishop.checkout package com.example.minishop.checkout
import com.example.minishop.cart.CartRepository @Deprecated("Lesson 7 moved checkout orchestration into ShopViewModel")
import com.example.minishop.model.Product class CheckoutService
import kotlin.random.Random
data class CheckoutResult(
val success: Boolean,
val message: String
)
class CheckoutService(
private val cartRepository: CartRepository
) {
fun totalPrice(productMap: Map<String, Product>): Double {
return cartRepository.items().sumOf { item ->
val product = productMap[item.productId] ?: return@sumOf 0.0
product.price * item.quantity
}
}
fun checkout(productMap: Map<String, Product>): CheckoutResult {
val total = totalPrice(productMap)
if (total <= 0.0) return CheckoutResult(false, "购物车为空")
val success = Random.nextBoolean()
return if (success) {
cartRepository.clear()
CheckoutResult(true, "结算成功(模拟),金额:¥${"%.2f".format(total)}")
} else {
CheckoutResult(false, "结算失败(模拟),请重试")
}
}
}
@@ -0,0 +1,11 @@
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
expect class DatabaseFactory() {
fun createDriver(): SqlDriver
}
fun createShopDatabase(factory: DatabaseFactory = DatabaseFactory()): ShopDatabase {
return ShopDatabase(factory.createDriver())
}
@@ -0,0 +1,17 @@
package com.example.minishop.order
data class OrderItem(
val productId: String,
val title: String,
val price: Double,
val imageUrl: String,
val quantity: Int
)
data class ShopOrder(
val orderId: String,
val totalPrice: Double,
val status: String,
val createdAt: Long,
val items: List<OrderItem>
)
@@ -0,0 +1,78 @@
package com.example.minishop.order
import com.example.minishop.cart.CartItem
import com.example.minishop.db.ShopDatabase
import com.example.minishop.platform.currentTimeMillis
import kotlin.random.Random
class OrderRepository(
private val database: ShopDatabase
) {
private val queries = database.ordersQueries
fun createOrder(cartItems: List<CartItem>): ShopOrder? {
if (cartItems.isEmpty()) return null
val orderId = buildOrderId()
val createdAt = currentTimeMillis()
val totalPrice = cartItems.sumOf { it.price * it.quantity }
val items = cartItems.map {
OrderItem(
productId = it.productId,
title = it.title,
price = it.price,
imageUrl = it.imageUrl,
quantity = it.quantity
)
}
queries.insertOrder(
order_id = orderId,
total_price = totalPrice,
status = "CREATED",
created_at = createdAt
)
items.forEach { item ->
queries.insertOrderItem(
order_id = orderId,
product_id = item.productId,
title = item.title,
price = item.price,
image_url = item.imageUrl,
quantity = item.quantity.toLong()
)
}
return ShopOrder(
orderId = orderId,
totalPrice = totalPrice,
status = "CREATED",
createdAt = createdAt,
items = items
)
}
fun getOrders(): List<ShopOrder> {
return queries.selectOrders().executeAsList().map { order ->
val items = queries.selectItemsByOrderId(order.order_id).executeAsList().map { item ->
OrderItem(
productId = item.product_id,
title = item.title,
price = item.price,
imageUrl = item.image_url,
quantity = item.quantity.toInt()
)
}
ShopOrder(
orderId = order.order_id,
totalPrice = order.total_price,
status = order.status,
createdAt = order.created_at,
items = items
)
}
}
private fun buildOrderId(): String = "ORD-${currentTimeMillis()}-${Random.nextInt(100, 999)}"
}
@@ -0,0 +1,3 @@
package com.example.minishop.platform
expect fun currentTimeMillis(): Long
@@ -0,0 +1,36 @@
CREATE TABLE cart_item (
product_id TEXT NOT NULL PRIMARY KEY,
title TEXT NOT NULL,
price REAL NOT NULL,
image_url TEXT NOT NULL,
quantity INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
selectAll:
SELECT *
FROM cart_item
ORDER BY updated_at DESC;
selectById:
SELECT *
FROM cart_item
WHERE product_id = ?;
insertOrReplace:
INSERT OR REPLACE INTO cart_item(
product_id,
title,
price,
image_url,
quantity,
updated_at
)
VALUES (?, ?, ?, ?, ?, ?);
deleteById:
DELETE FROM cart_item
WHERE product_id = ?;
deleteAll:
DELETE FROM cart_item;
@@ -0,0 +1,35 @@
CREATE TABLE shop_order (
order_id TEXT NOT NULL PRIMARY KEY,
total_price REAL NOT NULL,
status TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE order_item (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
order_id TEXT NOT NULL,
product_id TEXT NOT NULL,
title TEXT NOT NULL,
price REAL NOT NULL,
image_url TEXT NOT NULL,
quantity INTEGER NOT NULL
);
selectOrders:
SELECT *
FROM shop_order
ORDER BY created_at DESC;
insertOrder:
INSERT INTO shop_order(order_id, total_price, status, created_at)
VALUES (?, ?, ?, ?);
insertOrderItem:
INSERT INTO order_item(order_id, product_id, title, price, image_url, quantity)
VALUES (?, ?, ?, ?, ?, ?);
selectItemsByOrderId:
SELECT *
FROM order_item
WHERE order_id = ?
ORDER BY id ASC;
@@ -0,0 +1,10 @@
package com.example.minishop.db
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.native.NativeSqliteDriver
actual class DatabaseFactory actual constructor() {
actual fun createDriver(): SqlDriver {
return NativeSqliteDriver(ShopDatabase.Schema, "shop.db")
}
}
@@ -0,0 +1,5 @@
package com.example.minishop.platform
import platform.Foundation.NSDate
actual fun currentTimeMillis(): Long = (NSDate().timeIntervalSince1970 * 1000.0).toLong()