63 KiB
第7节|KMP 商城实操讲稿
主题:SQL 升级 + 最小 MVI + 订单闭环
本节严格按照《第6_7节课程大纲_确认版》推进。目标不是继续堆 UI, 而是把第6节“能跑”的商城项目,升级为更接近真实业务的数据层结构。
本节最终要做出的效果:
- 购物车从 Settings 升级到 SQL
- 完成“购物车 → 下单 → 订单列表”闭环
- 至少有 1 个核心页面按最小 MVI 管理状态
- 统一错误呈现,减少异常处理分散
一、本节课前准备
1. 环境要求
- JDK 17
- Android Studio 最新稳定版
- Android 模拟器或真机
- 项目已经完成第6节内容:
- 商品列表网络请求
- 购物车本地持久化(Settings)
- Android 页面能展示商品并加购
2. 本节重要提醒
本节会引入 SQLDelight。 所以课堂上要强调:
- 第6节的 Settings 方案没有错
- 但它更适合保存“少量配置 / 轻量 key-value 数据”
- 如果要继续做购物车扩展、订单记录、历史数据
- 就应该升级到 SQL
3. 本节对应官方文档
SQLDelight 官方文档
- Getting Started:
https://sqldelight.github.io/sqldelight/2.2.1/multiplatform_sqlite/ - Android Driver:
https://sqldelight.github.io/sqldelight/2.2.1/android_sqlite/ - Native Driver(iOS):
https://sqldelight.github.io/sqldelight/2.2.1/native_sqlite/
课堂说明怎么讲
不要只告诉学生“照着抄”。 要明确讲这三件事:
- SQLDelight 是 Kotlin Multiplatform 项目里常用的 SQL 方案
- 它的优势是:
- 用
.sq文件写 SQL - 自动生成类型安全的 Queries
- Android / iOS 都能共用数据库访问层
- 用
- 这节课不是讲数据库理论,而是讲:
- 为什么这里该用 SQL
- 怎么把它安全接进现有项目
二、本节开场(建议 3~5 分钟)
第6节我们已经完成了:
- 商品列表网络请求
- 购物车本地持久化
- 基础页面交互
但现在项目还停留在“能跑”的阶段。 如果继续往真实业务推进,就会遇到两个问题:
-
Settings 不适合复杂业务数据
- 它适合保存登录态、主题、开关项
- 但不适合长期管理购物车、订单、历史记录
-
状态管理会越来越乱
- Loading / Error / Empty / Success 混在一起
- 页面越做越多,越难维护
所以第7节要做的,不是继续加几个按钮, 而是把项目底层升级到更合理的结构。
三、Step 1:为什么要从 Settings 升级到 SQL
本步目标
让学生理解: 第7节引入 SQL,不是为了“更高级”,而是因为业务已经逼着我们升级。
这一段课堂要讲的内容
1)Settings 适合什么
Settings 更适合:
- 登录态
- 开关项
- 主题配置
- 少量轻量缓存
它本质上是: 保存一个 key 对应一个 value。
2)SQL 适合什么
SQL 更适合:
- 一组结构化数据
- 增删改查
- 排序 / 筛选 / 统计
- 多对象之间的业务关系
3)放到当前商城项目里怎么理解
在当前项目里:
- 购物车:适合 SQL
- 订单记录:更适合 SQL
- 后续收藏 / 地址 / 浏览记录,也更适合 SQL
- 商品接口仍然可以先保持网络请求,不强行在这节课扩展缓存体系
4)给学生的结论
可以直接把这句话讲给学生:
Settings 解决的是“存一个值”, SQL 解决的是“管理一组业务数据”。
本步课堂输出
到这里,学生应该明确:
- 第6节 Settings 方案没有问题
- 但第7节要继续做订单、历史记录时,必须升级到 SQL
本步暂时不写代码
这一部分先讲清楚动机,不着急改文件。 因为如果学生不知道为什么要改,后面代码只会机械复制。
四、Step 2:接入 SQLDelight
本步目标
把 SQLDelight 正确接入现有 KMP 项目,让后面可以:
- 写
.sq表结构 - 生成数据库类
- 在 Android / iOS 上分别创建 driver
本步会改哪些内容
本步只改依赖和插件,不改业务代码:
gradle/libs.versions.tomlshared/build.gradle.kts
先给学生讲:SQLDelight 是怎么工作的
你可以这样解释:
- 我们先在 Gradle 里加 SQLDelight plugin
- 再加 Android / iOS 各自的数据库 driver
- 再在
shared/src/commonMain/sqldelight/下写.sq文件 - SQLDelight 会自动生成:
- 数据库类
- Queries 类
- SQL 对应的数据模型
- 我们最后在 Repository 里调用这些 Queries
这一段一定要讲,不然学生会不知道: “为什么我只是写了 SQL,Kotlin 里会自动多出一堆类?”
Step 2.1:修改 gradle/libs.versions.toml
文件路径
kmp-mini-shopping/gradle/libs.versions.toml
修改目标
新增:
- SQLDelight 版本号
- Android Driver
- Native Driver
- SQLDelight plugin
完整代码(直接替换对应部分)
[versions]
agp = "8.9.3"
androidx-activityCompose = "1.10.1"
androidx-navigationCompose = "2.9.0"
androidx-ui-tooling = "1.8.3"
androidx-viewmodelCompose = "2.9.1"
coil = "3.2.0"
compose-multiplatform = "1.8.2"
kmpObservableViewmodel = "1.0.0-BETA-12"
kmpNativeCoroutines = "1.0.0-ALPHA-45"
koin = "4.1.0"
kotlin = "2.2.0"
kotlinx-serialization = "1.8.1"
ksp = "2.2.0-2.0.2"
ktor = "3.1.3"
multiplatform-settings = "1.1.1"
sqldelight = "2.2.1"
[libraries]
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" }
androidx-compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling", version.ref = "androidx-ui-tooling" }
androidx-compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview", version.ref = "androidx-ui-tooling" }
androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "androidx-navigationCompose" }
androidx-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "androidx-viewmodelCompose" }
coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }
coil-network-ktor = { group = "io.coil-kt.coil3", name = "coil-network-ktor3", version.ref = "coil" }
kmp-observable-viewmodel = { module = "com.rickclephas.kmp:kmp-observableviewmodel-core", version.ref = "kmpObservableViewmodel" }
koin-androidx-compose = { module = "io.insert-koin:koin-androidx-compose", version.ref = "koin" }
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core", version.ref = "kotlinx-serialization" }
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", 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" }
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]
androidApplication = { id = "com.android.application", version.ref = "agp" }
androidLibrary = { id = "com.android.library", version.ref = "agp" }
composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "compose-multiplatform" }
kmpNativeCoroutines = { id = "com.rickclephas.kmp.nativecoroutines", version.ref = "kmpNativeCoroutines" }
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlinxSerialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" }
Step 2.1 讲解重点
为什么要加两个 driver?
因为 KMP 项目最终要跑在多个平台:
- Android 端需要
android-driver - iOS 端需要
native-driver
为什么 plugin 要单独加?
因为 SQLDelight 不只是一个普通依赖。 它还要:
- 扫描
.sq文件 - 自动生成数据库类和 Queries
所以必须加 plugin,不能只加 library。
Step 2.2:修改 shared/build.gradle.kts
文件路径
kmp-mini-shopping/shared/build.gradle.kts
修改目标
- 给
shared模块加 SQLDelight plugin - 给 Android / iOS sourceSet 加 driver
- 配置数据库生成类名和包名
完整代码(整文件直接替换)
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.androidLibrary)
alias(libs.plugins.kotlinxSerialization)
alias(libs.plugins.ksp)
alias(libs.plugins.kmpNativeCoroutines)
alias(libs.plugins.sqldelight)
}
kotlin {
androidTarget {
@OptIn(ExperimentalKotlinGradlePluginApi::class)
compilerOptions {
jvmTarget.set(JvmTarget.JVM_11)
}
}
listOf(
iosX64(),
iosArm64(),
iosSimulatorArm64()
).forEach { iosTarget ->
iosTarget.binaries.framework {
baseName = "Shared"
isStatic = true
}
}
sourceSets {
androidMain.dependencies {
implementation(libs.ktor.client.okhttp)
implementation(libs.sqldelight.android.driver)
}
iosMain.dependencies {
implementation(libs.ktor.client.darwin)
implementation(libs.sqldelight.native.driver)
}
commonMain.dependencies {
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.content.negotiation)
implementation(libs.ktor.serialization.kotlinx.json)
implementation(libs.multiplatform.settings.no.arg)
implementation(libs.koin.core)
api(libs.kmp.observable.viewmodel)
}
all {
languageSettings.optIn("kotlinx.cinterop.ExperimentalForeignApi")
languageSettings.optIn("kotlin.experimental.ExperimentalObjCName")
}
}
}
sqldelight {
databases {
create("ShopDatabase") {
packageName.set("com.example.minishop.db")
}
}
}
android {
namespace = "com.example.minishop.shared"
compileSdk = 35
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
defaultConfig {
minSdk = 24
}
}
Step 2.2 讲解重点
1)为什么把 SQLDelight 放在 shared 模块
因为数据库访问属于共享业务层。
这节课我们要做的购物车、订单、商品缓存,
本质上都不是 Android 独有能力,
所以应该放在 shared,而不是 composeApp。
2)create("ShopDatabase") 是什么意思
这表示 SQLDelight 会生成一个数据库类,名字叫:
ShopDatabase
后面 Repository 里就会通过这个类拿到 Queries。
3)为什么要指定 packageName
因为 SQLDelight 生成的类需要一个明确包名。
这里我们统一放到:
com.example.minishop.db
这样后面:
DatabaseFactoryCartRepositoryOrderRepository
都可以围绕这个包来组织。
Step 2.3:同步 Gradle / 生成 SQLDelight 类
这一步要做什么
完成前两步之后,让学生执行一次:
- Sync Gradle
- 让项目识别 SQLDelight plugin
- 为后面
.sq文件生成代码做好准备
建议操作
在 Android Studio 中:
- 点击 Sync Project with Gradle Files
如果学生用命令行,可以执行:
./gradlew tasks
或者后续在写完 .sq 文件后执行:
./gradlew :shared:generateSqlDelightInterface
Step 2.3 验收标准
到这里不需要业务功能已经完成。 本步的验收只有两个:
- Gradle Sync 不报 SQLDelight plugin 未找到
shared模块已经具备后续写.sq文件的能力
五、本步常见报错与处理
1)Plugin [id: 'app.cash.sqldelight'] was not found
说明通常是以下原因之一:
libs.versions.toml里没有加sqldelightpluginshared/build.gradle.kts没有alias(libs.plugins.sqldelight)- Gradle 没有重新 sync
2)Unresolved reference: libs.sqldelight.android.driver
说明通常是:
libs.versions.toml里没有加 library 别名- 名字写错
- 还没同步 Gradle
3)Android Gradle Plugin 拉取失败
如果课堂环境里遇到 AGP 版本解析失败,先做这两件事:
- 确认网络能访问 Google Maven
- 如果当前项目模板版本过新,统一切到课堂验证通过的稳定版本
这类问题属于工程环境问题,不是 SQLDelight 本身的问题。 上课时最好提前准备一份已验证可同步的项目基线。
六、本步小结
到这里为止,我们还没有正式开始写购物车表和订单表。 但已经完成了第7节最重要的起步工作:
- 知道为什么第7节必须从 Settings 升级到 SQL
- 知道 SQLDelight 是什么
- 知道怎么把 SQLDelight 接进 KMP 项目
- 知道后面
.sq文件会生成哪些 Kotlin 类
接下来下一步,才是正式开始建表:
- 购物车表
- 订单表
- 订单明细表
七、本节整体顺序(重新整理后的主线)
去掉“离线优先”后,第7节建议严格按下面顺序推进:
- 为什么从 Settings 升级到 SQL
- 接入 SQLDelight
- 建立购物车表 / 订单表 / 订单明细表
- 把 CartRepository 从 Settings 改成 SQL
- 增加 OrderRepository,完成下单闭环
- 在商品列表页落最小 MVI
- 统一错误结构与错误展示
- 课堂验收与课后作业
这样讲的好处是:
- 先解决“为什么改”
- 再解决“怎么接技术”
- 再解决“业务怎么落地”
- 最后再收状态管理和错误处理
八、Step 3:建立购物车表、订单表、订单明细表
本步目标
这一部分开始真正进入 SQL 落地。 完成之后,学生应该能明确三件事:
- 第7节到底要建哪几张表
- 每张表分别承担什么业务职责
.sq文件应该放在哪里、怎么写、写完后会生成什么
这一段先讲什么
先别急着贴 SQL,先告诉学生:
为什么第7节至少需要三张表?
因为本节不是只想把“购物车存起来”,而是要补齐一个最小业务闭环:
- 商品加入购物车
- 购物车生成订单
- 一个订单包含多条商品项
如果只建一张购物车表,后面没法优雅表示订单。 如果只有订单表,没有订单明细表,后面展示订单内容会很别扭。
所以这节课最合理的最小建模是:
cart_item:购物车表shop_order:订单表order_item:订单明细表
Step 3.1:先讲 SQLDelight 的 .sq 文件放哪里
文件路径规则
这节课统一放在:
shared/src/commonMain/sqldelight/com/example/minishop/db/
为什么放这里
因为:
shared是共享业务层commonMain表示 Android / iOS 共用sqldelight/.../db/这一层路径要和我们前面配置的packageName对应
前面在 shared/build.gradle.kts 里已经写了:
sqldelight {
databases {
create("ShopDatabase") {
packageName.set("com.example.minishop.db")
}
}
}
所以这里的 SQL 文件路径也要围绕这个包来组织。
Step 3.2:创建购物车表 Cart.sq
购物车表为什么要这些字段
学生在这里最容易问:
“为什么购物车表不只存 productId + quantity?”
课堂上建议这样讲:
如果只存 productId + quantity,后面每次展示购物车都还要再反查商品信息。
为了让本节课更顺滑、闭环更完整,这里直接把展示购物车需要的关键字段一起存下来:
product_idtitlepriceimage_urlquantityupdated_at
这样做的好处:
- 购物车页展示更直接
- 后面生成订单明细也更方便
- 对课堂 demo 更友好
文件路径
shared/src/commonMain/sqldelight/com/example/minishop/db/Cart.sq
完整代码
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;
这一段要给学生强调什么
PRIMARY KEY放在product_id- 因为一个商品在购物车里只保留一条记录
INSERT OR REPLACE- 很适合做购物车数量更新
updated_at- 让购物车列表后面可以按最近修改时间排序
本步验收
写完后先不要求页面已经用上。 只要做到:
- 文件路径正确
- SQL 语法正确
- 能被 SQLDelight 识别
Step 3.3:创建订单表 Orders.sq
为什么订单要拆成“订单表 + 订单明细表”
课堂上可以直接讲:
一个订单本身是一条业务记录, 但一个订单里可能有多个商品。
所以要拆成:
shop_order:记录订单本身order_item:记录订单里的商品项
这就是最常见的一对多关系。
文件路径
shared/src/commonMain/sqldelight/com/example/minishop/db/Orders.sq
完整代码
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;
这一段要给学生强调什么
shop_order记录的是“订单本身”order_item记录的是“订单中的商品列表”- 本节课先不深讲外键约束、复杂事务、支付状态流转
- 先把最小闭环讲清楚最重要
本步验收
写完后应当能回答这两个问题:
- 为什么订单不能只用一张表?
- 一个订单对应多条商品记录时,为什么要单独建
order_item?
Step 3.4:生成 SQLDelight 代码
这一步做什么
当前已经写好了两份 .sq:
Cart.sqOrders.sq
现在要让 SQLDelight 生成 Kotlin 代码。
建议操作
在 Android Studio 中:
- 重新 Sync Gradle
如果用命令行:
./gradlew :shared:generateSqlDelightInterface
生成后会出现什么
后面在 Kotlin 代码里,就可以使用类似这些生成对象:
ShopDatabase
cartQueries
ordersQueries
具体类名会根据
.sq文件内容和create("ShopDatabase")自动生成。
Step 3.5:本步常见问题
1).sq 文件放错目录
如果学生把文件放到了:
shared/src/commonMain/kotlin/...- 或者少了
sqldelight/
那 SQLDelight 根本不会识别。
2)SQL 写了但没有生成类
检查:
- 是否已经 Sync Gradle
- 是否执行过
generateSqlDelightInterface shared/build.gradle.kts里是否已有sqldelight { ... }
3)字段名为什么要用下划线
例如:
product_idimage_urlcreated_at
课堂上建议统一说明:
- SQL 层用下划线命名更常见
- Kotlin 层后面再映射成更顺手的字段名
这样学生不会在命名风格上来回打架。
Step 3.6:本步小结
到这里,学生已经完成了第7节数据层升级里最关键的一步:
- 购物车表建好了
- 订单表建好了
- 订单明细表建好了
- SQLDelight 已经知道要生成哪些 Queries
接下来下一步就可以进入真正的 Repository 改造:
- 把
CartRepository从 Settings 改成 SQL - 增加
OrderRepository
九、Step 4:把 CartRepository 从 Settings 改成 SQL
本步目标
这一部分是第7节真正开始“把业务接到 SQL 上”。
完成后,学生应该能理解:
- 为什么 Repository 仍然要保留
- 为什么不是 UI 直接调用 SQLDelight 生成的 Queries
- 购物车从 Settings 切到 SQL 时,哪些代码要一起调整
本步会改到这些文件:
shared/src/commonMain/kotlin/com/example/minishop/db/DatabaseFactory.ktshared/src/androidMain/kotlin/com/example/minishop/db/AppContext.ktshared/src/androidMain/kotlin/com/example/minishop/db/DatabaseFactory.android.ktshared/src/iosMain/kotlin/com/example/minishop/db/DatabaseFactory.ios.ktshared/src/commonMain/kotlin/com/example/minishop/cart/CartItem.ktshared/src/commonMain/kotlin/com/example/minishop/cart/CartRepository.ktshared/src/commonMain/kotlin/com/example/minishop/cart/CartStorage.ktcomposeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.ktcomposeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.ktcomposeApp/src/androidMain/kotlin/com/example/minishop/App.kt
Step 4.1:先补数据库入口(DatabaseFactory)
为什么这一步必须先做
前面虽然已经写好了 .sq 文件,
但如果没有数据库 driver 和数据库实例入口,CartRepository 根本没法拿到:
ShopDatabase
所以这一小步不是“附属工作”,而是 SQL 版 Repository 的前置条件。
先补一个时间函数提醒
因为本步里的 CartRepository 需要记录 updated_at,
我们这里不额外引入 kotlinx-datetime,而是直接在共享层补一个平台时间函数。
这样做的好处:
- 课堂更直接
- 依赖更少
- 学生更容易理解
expect / actual的实际用途
文件1:shared/src/commonMain/kotlin/com/example/minishop/db/DatabaseFactory.kt
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())
}
文件2:shared/src/commonMain/kotlin/com/example/minishop/platform/Time.kt
package com.example.minishop.platform
expect fun currentTimeMillis(): Long
文件3:shared/src/androidMain/kotlin/com/example/minishop/platform/Time.android.kt
package com.example.minishop.platform
actual fun currentTimeMillis(): Long = System.currentTimeMillis()
文件4:shared/src/iosMain/kotlin/com/example/minishop/platform/Time.ios.kt
package com.example.minishop.platform
import platform.Foundation.NSDate
actual fun currentTimeMillis(): Long = (NSDate().timeIntervalSince1970 * 1000.0).toLong()
文件5:shared/src/androidMain/kotlin/com/example/minishop/db/AppContext.kt
package com.example.minishop.db
import android.content.Context
lateinit var appContext: Context
private set
fun initAppContext(context: Context) {
appContext = context.applicationContext
}
文件6:shared/src/androidMain/kotlin/com/example/minishop/db/DatabaseFactory.android.kt
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")
}
}
文件7:shared/src/iosMain/kotlin/com/example/minishop/db/DatabaseFactory.ios.kt
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")
}
}
这一段课堂要强调什么
expect / actual是 KMP 平台实现差异的典型用法- 公共层只关心“我要一个 driver”
- Android / iOS 各自决定 driver 怎么创建
Step 4.2:把 CartItem 从“极简数量模型”升级成“可展示购物车模型”
为什么要改 CartItem
第6节的 CartItem 只需要:
productIdquantity
因为当时只是把购物车用 Settings 存起来。
但第7节切到 SQL 后,购物车表里已经存了:
- 标题
- 单价
- 图片
所以 CartItem 也应该升级成更适合 UI 和业务层使用的结构。
文件路径
shared/src/commonMain/kotlin/com/example/minishop/cart/CartItem.kt
完整代码
package com.example.minishop.cart
data class CartItem(
val productId: String,
val quantity: Int,
val title: String,
val price: Double,
val imageUrl: String
)
课堂要点
这里可以顺手提醒学生:
- SQL 层字段是下划线命名
- Kotlin 层模型还是 camelCase 更顺手
- Repository 的职责之一,就是做这种映射
Step 4.3:把 CartRepository 改成 SQL 版
为什么 Repository 不能删掉
很多学生会问:
既然 SQLDelight 已经生成 cartQueries 了,为什么不直接在页面里调用?
这里要明确讲:
- UI 不应该直接碰数据库
- Repository 是数据访问的统一入口
- 后面如果 SQL 再变、规则再变,上层不用大改
文件路径
shared/src/commonMain/kotlin/com/example/minishop/cart/CartRepository.kt
完整代码
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(
private val database: ShopDatabase
) {
private val queries = database.cartQueries
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(product: Product) {
val current = queries.selectById(product.id).executeAsOneOrNull()
val nextQuantity = (current?.quantity?.toInt() ?: 0) + 1
upsert(product, nextQuantity)
}
fun increase(productId: String) {
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
queries.insertOrReplace(
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) {
val current = queries.selectById(productId).executeAsOneOrNull() ?: return
val next = current.quantity.toInt() - 1
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) {
queries.deleteById(productId)
}
fun clear() {
queries.deleteAll()
}
private fun upsert(product: Product, quantity: Int) {
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()
}
这一段课堂要强调什么
items()负责把 SQL 行映射成CartItemadd(product: Product)改成接收整个商品,而不是只传productId- 因为现在购物车表要把展示字段一起存下来
Step 4.4:旧的 CartStorage 怎么处理
为什么要处理这个文件
如果这个文件继续保留第6节的序列化实现,
它会和新的 CartItem 结构不一致。
所以这一步建议直接改成“保留文件名,但不再承担实际功能”, 既能让学生知道第6节方案已经退场, 也不会让项目因为旧代码报错。
文件路径
shared/src/commonMain/kotlin/com/example/minishop/cart/CartStorage.kt
完整代码
package com.example.minishop.cart
@Deprecated("Lesson 7 switched cart persistence from Settings to SQLDelight")
class CartStorage
课堂说明
你可以直接告诉学生:
- 第6节它是真的在用
- 第7节开始它只是“历史痕迹”
- 这节课的真实购物车持久化已经交给 SQLDelight 了
Step 4.5:把总价计算收回 ShopViewModel
为什么这里也要改
当前这节课里,下单逻辑和总价计算都只服务于当前页面流程,
如果单独抽一个 CheckoutService,反而会让分层显得有点虚。
所以第7节这里更自然的做法是:
Repository只负责数据访问ShopViewModel直接负责编排总价计算和结算动作
这样对学生来说更直观,也更符合“教学最小闭环”。
课堂说明
你可以直接告诉学生:
- 现在业务还很轻
- 只有一个页面在用结算逻辑
- 所以先不额外抽 Service / UseCase
- 等以后有库存、优惠券、支付等更复杂逻辑时,再考虑上移成独立 UseCase
Step 4.6:Android 入口补上 appContext
为什么这一步不能漏
因为 Android 版 DatabaseFactory 用到了:
AndroidSqliteDriver(ShopDatabase.Schema, appContext, "shop.db")
所以应用启动时必须先初始化 appContext。
文件路径
composeApp/src/androidMain/kotlin/com/example/minishop/MainActivity.kt
完整代码
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)
setContent {
App()
}
}
}
Step 4.7:让 ShopViewModel 接 SQL 版购物车并自己计算总价
为什么 ViewModel 也得改
因为 CartRepository 的构造方式已经变了:
- 以前:
CartRepository() - 现在:
CartRepository(database)
并且加购方法也变了:
- 以前:
add(productId) - 现在:
add(product)
文件路径
composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt
完整代码
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.db.createShopDatabase
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 database = createShopDatabase()
private val cartRepository = CartRepository(database)
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(product: Product): String {
cartRepository.add(product)
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 {
return "第4步这里先不真正下单,第5步再接订单闭环"
}
private fun syncCart() {
val items = cartRepository.items()
uiState = uiState.copy(
cartItems = items,
totalCount = items.sumOf { it.quantity },
totalPrice = items.sumOf { it.price * it.quantity }
)
}
override fun onCleared() {
scope.cancel()
super.onCleared()
}
}
Step 4.8:让 App.kt 使用 SQL 版 CartItem
为什么 UI 这里也要微调
因为现在购物车项里已经带了:
titleprice
所以购物车页没必要再依赖 productMap 才能展示标题和金额。
这一步课堂建议
这一段不要整文件重贴,学生太容易淹死。 你可以只告诉学生改这两处:
改动1:商品列表和详情页的加购回调
把:
vm.addToCart(it.id)
改成:
vm.addToCart(it)
改动2:购物车页直接使用 CartItem 自带字段
把 CartScreen 的参数从:
productMap: Map<String, Product>
收掉,改为直接使用:
item.titleitem.price
推荐替换后的 CartScreen
@Composable
private fun CartScreen(
items: List<CartItem>,
totalPrice: Double,
onInc: (String) -> Unit,
onDec: (String) -> Unit,
onRemove: (String) -> Unit,
onClear: () -> Unit,
onCheckout: () -> Unit
) {
Box(
Modifier
.fillMaxSize()
.padding(horizontal = 16.dp, vertical = 12.dp)
) {
if (items.isEmpty()) {
EmptyState("购物车为空")
} else {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(bottom = 96.dp)
) {
items(items) { item ->
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text(item.title, fontWeight = FontWeight.Medium)
Text("¥${formatPrice(item.price * item.quantity)}")
}
Row(verticalAlignment = Alignment.CenterVertically) {
SmallOpButton("-") { onDec(item.productId) }
Text(" ${item.quantity} ")
SmallOpButton("+") { onInc(item.productId) }
Spacer(Modifier.width(8.dp))
OutlinedButton(onClick = { onRemove(item.productId) }) { Text("移除") }
}
}
}
}
}
Card(
modifier = Modifier
.align(Alignment.BottomCenter)
.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(12.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column {
Text("总件数:${items.sumOf { it.quantity }}")
Text("合计:¥${formatPrice(totalPrice)}", fontWeight = FontWeight.Bold)
}
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = onClear) { Text("清空") }
Button(onClick = onCheckout) { Text("结算") }
}
}
}
}
}
}
Step 4.9:本步验收
到这一步,课堂上至少要看到这些结果:
- 加购之后,购物车记录来自 SQL 表,而不是 Settings
- 重启 App 后,购物车数据还能恢复
- 购物车页能直接显示标题、数量、金额
CartRepository已经不再依赖第6节的CartStorage
Step 4.10:本步小结
到这里,学生已经完成第7节里第一个真正的数据层升级动作:
- SQL 表不是只写着摆设
- 购物车已经真正切到 SQL
- UI 仍然通过 Repository 拿数据
- ViewModel 和页面只是做最小适配
接下来下一步,就可以开始新增 OrderRepository,把“下单 → 订单列表”闭环接起来。
十、Step 5:增加 OrderRepository,打通“下单 → 订单列表”闭环
本步目标
到这一步,第7节终于开始进入“像真实商城一点”的阶段。
完成后,学生应该能看到:
- 点击结算不再只是随机弹一句提示
- 购物车可以真正生成订单
- 下单后购物车被清空
- 订单列表页能看到刚刚生成的订单
也就是说,本步的目标不是“理论上支持订单”, 而是把最小订单闭环真正跑通。
Step 5.1:先补订单模型
为什么还要单独建 Kotlin 模型
虽然 SQLDelight 已经能生成查询结果类型, 但课堂里还是建议再封装一层:
ShopOrderOrderItem
这样做有两个好处:
- UI 层读起来更直观
- 后面如果数据库字段变了,页面层不一定跟着一起乱
文件路径
shared/src/commonMain/kotlin/com/example/minishop/order/OrderModels.kt
完整代码
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>
)
Step 5.2:增加 OrderRepository
为什么这一步不能省
很多学生会觉得:
“下单的时候直接在 ViewModel 里调用 ordersQueries.insertOrder() 不就行了?”
这节课一定要强调:
- 不能让 ViewModel 直接操作数据库细节
- 订单的创建过程有多步:
- 写订单主表
- 写订单明细表
- 这种逻辑应该收进 Repository
文件路径
shared/src/commonMain/kotlin/com/example/minishop/order/OrderRepository.kt
完整代码
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)}"
}
这一段课堂要强调什么
createOrder()不只是返回一个对象,而是真的把订单写进数据库- 订单主表和订单明细表要一起写
getOrders()负责把数据库查询结果重新组装成适合 UI 使用的结构
Step 5.3:让 ShopViewModel 直接编排下单流程
为什么这里不再保留 CheckoutService
到这一步我们重新梳理一下分层,会发现:
CartRepository负责购物车数据OrderRepository负责订单数据- 下单逻辑目前只服务于当前页面流程
如果这里再夹一层很薄的 CheckoutService,反而会让学生多记一个抽象。
所以第7节里更自然的方案是:
Repository负责数据访问ShopViewModel直接负责编排:- 读取购物车
- 创建订单
- 清空购物车
- 刷新订单列表
- 切换到订单页
课堂结论
当前业务还不复杂时,直接放在 ViewModel 里会比额外抽一个薄 Service 更自然。
Step 5.4:让 ViewModel 同时管理购物车和订单
为什么 ViewModel 这里要扩一下
因为这一步之后,页面上不只要展示:
- 商品列表
- 购物车
还要展示:
- 订单列表
所以 ShopUiState 里也要加订单状态。
文件路径
composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt
本步关键改动
- 增加
orders: List<ShopOrder> - 增加
orderRepository checkout()成功后刷新订单列表- 下单成功后切到订单页
完整代码
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.db.createShopDatabase
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 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,
val orders: List<ShopOrder> = emptyList()
)
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 database = createShopDatabase()
private val cartRepository = CartRepository(database)
private val orderRepository = OrderRepository(database)
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()
syncOrders()
}
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(product: Product): String {
cartRepository.add(product)
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 cartItems = cartRepository.items()
if (cartItems.isEmpty()) {
return "购物车为空"
}
val order = orderRepository.createOrder(cartItems)
?: return "创建订单失败"
cartRepository.clear()
syncCart()
syncOrders()
uiState = uiState.copy(currentTab = Tab.Orders)
return "下单成功,订单号:${order.orderId}"
}
private fun syncCart() {
val items = cartRepository.items()
uiState = uiState.copy(
cartItems = items,
totalCount = items.sumOf { it.quantity },
totalPrice = items.sumOf { it.price * it.quantity }
)
}
private fun syncOrders() {
uiState = uiState.copy(orders = orderRepository.getOrders())
}
override fun onCleared() {
scope.cancel()
super.onCleared()
}
}
Step 5.5:新增订单列表页
为什么要加这个页面
如果这一步只做到“数据库里有订单”,学生是没有感知的。
课堂一定要让结果可见:
- 下单后切到订单页
- 页面里能直接看到订单号、总价、商品明细
这样学生才会真正感觉“订单闭环”做成了。
这一步最小改动思路
Tab增加Orders- 底部导航增加“订单”
- 新增
OrderScreen - checkout 成功后自动切过去
推荐的 OrderScreen
@Composable
private fun OrderScreen(orders: List<ShopOrder>) {
if (orders.isEmpty()) {
EmptyState("还没有订单")
return
}
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(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}")
}
}
}
}
}
}
Step 5.6:本步验收
这一步课堂上至少要看到这些现象:
- 商品加购后,购物车里有内容
- 点击“结算”后,不再只是随机提示
- 成功下单后:
- 购物车被清空
- 订单页能看到新订单
- 订单里能看到商品明细
如果学生做到这一步,其实第7节最重要的“订单闭环”就已经成立了。
Step 5.7:本步小结
到这里,第7节最关键的业务成果已经出来了:
- SQL 不只是替换了 Settings
- 它已经真正承载了订单业务
- 购物车 → 下单 → 订单列表 形成了完整链路
接下来就可以进入第7节剩下的两块:
- 最小 MVI
- 统一错误呈现
十一、Step 6 前导:先认识最小 MVI
为什么这里要先讲一点 MVI
如果直接让学生抄下面的代码,他们大概率会出现几个疑问:
- 为什么突然多了
Intent - 为什么不用原来那种
loading + error + products dispatch()到底在做什么- 这和我们现在已有的 ViewModel 是什么关系
所以在正式写 Step 6 代码之前,建议先用 5~10 分钟把“最小 MVI”讲清楚。
注意:这里不是上一整节 MVI 理论课, 而是只讲理解本节代码所必需的那一层。
Step 6 前导 1:一句话理解 MVI
可以直接这样讲给学生:
- Intent:用户做了什么
- State:页面现在是什么状态
- ViewModel / dispatch:把用户动作处理成新的页面状态
如果要画成最小流程图,就是:
用户操作
↓
Intent
↓
ViewModel / dispatch
↓
新的 State
↓
UI 根据 State 渲染
这张图不用展开太多,学生先建立直觉就够了。
Step 6 前导 2:为什么这节课要引入 MVI
因为到了第7节,商品列表页已经不只是“把数据画出来”这么简单了。 它同时有这些状态:
- 首次加载
- 加载失败
- 空数据
- 正常显示
- 搜索过滤后显示
如果还继续用:
loading: BooleanloadError: String?products: List<Product>
这种散装组合方式,状态越多越乱。
所以这节课引入 MVI 的目的不是“为了追新架构”, 而是为了让页面状态更清晰、更容易维护。
Step 6 前导 3:这节课里的 MVI 范围有多大
这句一定要明确说,不然学生会以为要全项目大重构:
本节只做
- 商品列表页的最小 MVI
- 只引入最核心的三个概念:
- Intent
- State
- 统一状态流转入口
本节不做
- 不把整个 App 全部改成 MVI
- 不展开讲完整 Redux / Elm / UDF 理论
- 不拆一大堆 reducer / store / middleware 文件
也就是说:
第7节里的 MVI 是“够用就好”的版本,重点是让学生第一次看懂它怎么落地。
Step 6 前导 4:它和现在的 ViewModel 是什么关系
这一步也值得讲清楚。
本节并不是把原来的 ViewModel 推翻重写, 而是在现有 ViewModel 的基础上做一层升级:
- 原来:ViewModel 里散落多个状态字段
- 现在:让列表页状态先收成一个
ProductListState - 原来:页面零散调用多个方法
- 现在:页面更倾向通过
dispatch(intent)发动作
所以你可以直接告诉学生:
这节课不是“MVVM 不用了”, 而是在现有 ViewModel 基础上,引入更清晰的状态组织方式。
Step 6 前导 5:为什么商品列表页最适合当示例
因为它天然就有四种非常标准的页面状态:
LoadingSuccessErrorEmpty
而且它还正好有几种典型动作:
- 首次加载
- 点击重试
- 点击加购
- 输入搜索词
所以它比购物车页、订单页更适合拿来做第一个 MVI 示例。
Step 6 前导小结
到这里,学生不需要会背架构理论, 只需要先记住下面这句话:
MVI 的核心,就是把“用户动作”和“页面状态”明确分开, 然后用一个统一入口去管理状态变化。
接下来再进入真正的 Step 6 代码,学生就不会觉得是突然变魔术。
十二、Step 6:把商品列表页改成最小 MVI
本步目标
这一步不是把整个项目都改造成 MVI, 而是只挑一个最适合演示状态管理的页面:商品列表页。
完成后,学生应该能理解:
- 什么是 Intent
- 什么是 State
- 为什么页面状态不要散在一堆布尔值里
- MVI 最小落地长什么样
课堂上一定要强调:
第7节的 MVI 只是“最小状态管理示范”,不是整套架构革命。
Step 6.1:为什么商品列表页最适合演示 MVI
商品列表页天然就有四种很典型的状态:
LoadingSuccessErrorEmpty
另外它还正好有几种用户动作:
- 首次加载
- 点击重试
- 点击加购
- 输入搜索词
所以非常适合拿来做最小 MVI 示例。
Step 6.2:先定义列表页的 Intent 和 State
文件路径
composeApp/src/androidMain/kotlin/com/example/minishop/ShopViewModel.kt
为什么要先定义这两个
很多学生一上来就会直接开始改 refreshProducts(),
但如果不先把:
- Intent
- State
这两个概念定义清楚,最后很容易又回到“到处散落状态变量”的写法。
建议新增的代码
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 里有:
productsloadingloadError
这种写法在简单页面还能忍, 但状态一多,很快就会出现:
loading = falseloadError != nullproducts又不是空
这种状态组合不清晰的问题。
建议改法
把列表状态收成一个字段:
val productListState: ProductListState = ProductListState.Loading
然后 products 仍然保留在 ShopUiState 里,
这样搜索、详情、购物车数量统计都还能复用。
Step 6.4:在 ViewModel 里增加 dispatch()
为什么这一步是 MVI 的关键
前面只是定义了概念, 真正让它变成最小 MVI 的,是增加一个统一入口:
fun dispatch(intent: ProductListIntent)
这样之后:
- 加载
- 重试
- 搜索
- 加购
都不再是页面零散地直接调用一堆方法, 而是统一走 Intent。
建议写法
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
核心写法
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 已经给了:
LoadingSuccessErrorEmpty
那 UI 层就应该只关心“当前是什么状态”, 而不是自己再重复拼判断。
推荐思路
把原来 ProductListScreen 里的这几个参数:
loadingerrorproducts
收成:
state: ProductListState
然后按 when (state) 渲染。
课堂要点
这一步非常关键,因为学生会第一次明显感受到: 状态和 UI 是怎么一一对应起来的。
Step 6.7:搜索和加购为什么还要保留在这个页面里
这一步学生很容易问:
“既然都 MVI 了,为什么不把搜索结果也完全装进 State?”
课堂上建议你这样回答:
- 可以那样做
- 但本节课只做“最小 MVI”
- 我们只把最核心的页面状态收口
- 不把课堂复杂度一下拉太高
也就是说,这一节的重点是:
- 学生先理解 MVI 长什么样
- 而不是一口气把整个项目重构到最彻底
Step 6.8:本步验收
这一步做完后,学生至少应该能看到:
- 列表加载时显示
Loading - 请求失败时显示
Error + 重试 - 数据为空时显示
Empty - 数据正常时显示
Success - 搜索和加购还能正常工作
如果这一点能做到,就说明第7节里的“最小 MVI”已经落地了。
Step 6.9:本步小结
到这里,第7节其实已经完成了三件最重要的事:
- SQL 升级
- 订单闭环
- 最小 MVI 落地
剩下最后一块,就是把错误处理再统一收一下。
十二、本节整体顺序(重新整理后的主线)
去掉“离线优先”后,第7节建议严格按下面顺序推进:
- 为什么从 Settings 升级到 SQL
- 接入 SQLDelight
- 建立购物车表 / 订单表 / 订单明细表
- 把 CartRepository 从 Settings 改成 SQL
- 增加 OrderRepository,完成下单闭环
- 在商品列表页落最小 MVI
- 统一错误结构与错误展示
- 课堂验收与课后作业
这样讲的好处是:
- 先解决“为什么改”
- 再解决“怎么接技术”
- 再解决“业务怎么落地”
- 最后再收状态管理和错误处理
十三、下一步预告(Step 7)
下一步开始把错误处理统一收口:
- 共享层统一 Success / Error 结构
- ViewModel 不再到处散落错误文案
- UI 层统一消费错误状态和重试动作
并且继续保持本节文档风格:
- 先讲为什么
- 再贴完整代码
- 再给验收方式