跨平台方案很多:Flutter、React Native、Compose Multiplatform。Kotlin Multiplatform Mobile(KMM)走的是另一条路:UI 层各平台自己写,业务逻辑共享。
一、KMM 适合什么场景
KMM 不是“写一次跑所有平台”。它更适合:
两端业务逻辑重复度高
已经有原生 Android/iOS 团队
对 UI 体验要求高,不愿意牺牲原生控件
需要复用网络层、数据层、领域层
二、项目结构
shared/
src/
commonMain/ # 公共 Kotlin 代码
androidMain/ # Android 平台实现
iosMain/ # iOS 平台实现
commonMain 里写接口和通用逻辑,平台目录里写具体实现。
// commonMain
expect class Platform() {
val name: String
}
fun hello(): String = "Hello from ${Platform().name}"
// androidMain
actual class Platform actual constructor() {
actual val name: String = "Android ${android.os.Build.VERSION.SDK_INT}"
}
三、依赖注入与网络层
KMM 项目常用:
Ktor Client:跨平台网络请求
Kotlinx Serialization:跨平台序列化
Koin:跨平台依赖注入
SQLDelight:跨平台数据库
// shared/build.gradle.kts
commonMain.dependencies {
implementation("io.ktor:ktor-client-core:$ktorVersion")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:$serializationVersion")
}
四、共享 ViewModel
// shared
class NewsViewModel(private val repository: NewsRepository) : ViewModel() {
private val _uiState = MutableStateFlow(NewsUiState())
val uiState: StateFlow<NewsUiState> = _uiState.asStateFlow()
fun loadNews() {
viewModelScope.launch {
_uiState.update { it.copy(isLoading = true) }
val news = repository.fetchNews()
_uiState.update { it.copy(news = news, isLoading = false) }
}
}
}
Android 端直接用,iOS 端用 KMMViewModelSwiftUI 桥接到 SwiftUI。
五、KMM 的局限
UI 不能共享,需要两端各自实现
平台特定 API 要用 expect/actual 桥接
构建链比纯 Android 复杂
团队需要同时懂 Android 和 iOS
小结
KMM 共享业务层,不共享 UI
适合已有双端团队、业务逻辑重复度高的项目
Ktor、SQLDelight、Koin 是常用技术栈
UI 层仍需原生实现,不能把它当成 Flutter 用
30 篇过去了,这个系列已经从 Activity 生命周期走到了跨平台共享代码。后面我们会继续深入:性能监控、CI/CD、鸿蒙适配、大模型端侧集成。下篇见。
参考阅读
引用链接
[1]Kotlin Multiplatform 官方文档: https://www.jetbrains.com/help/kotlin-multiplatform-dev/get-started.html
[2]KMM 示例项目: https://github.com/Kotlin/kmm-basic-sample