Ktor 学习与实践文档

Kotlin Multiplatform (KMP) + Ktor 学习与实践文档

一、概述

Kotlin Multiplatform (KMP) 是 JetBrains 提供的跨平台开发方案,核心思想是逻辑层代码共享,UI 层保持原生。在 KMP 中,网络层通常使用 Ktor,这是一个由 JetBrains 开发的异步网络框架,天然支持多平台(Android、iOS、Desktop、Web)。

KMP + Ktor 的组合,能让我们用一套代码实现跨平台的网络请求逻辑。


二、Ktor 特性

  • 跨平台支持:Android 使用 OkHttp,iOS 使用 NSURLSession,桌面和 Web 也有各自实现。
  • 异步非阻塞:基于协程,性能高。
  • 模块化插件:支持 JSON 序列化、认证、日志、WebSocket 等。
  • 客户端与服务端统一:既能写客户端 SDK,也能写后端服务。

三、项目结构

KMP 项目典型结构:

1
2
3
4
5
shared/
├── commonMain/ # 共享逻辑 (Ktor 请求、Repository、UseCase)
├── androidMain/ # Android 平台特定实现
├── iosMain/ # iOS 平台特定实现
└── ...

commonMain 中编写网络请求逻辑,Android 与 iOS 会自动调用对应平台实现。


四、依赖配置

shared/build.gradle.kts 中添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
kotlin {
android()
iosX64()
iosArm64()
iosSimulatorArm64()

sourceSets {
val commonMain by getting {
dependencies {
implementation("io.ktor:ktor-client-core:3.0.0")
implementation("io.ktor:ktor-client-content-negotiation:3.0.0")
implementation("io.ktor:ktor-serialization-kotlinx-json:3.0.0")
}
}
val androidMain by getting {
dependencies {
implementation("io.ktor:ktor-client-okhttp:3.0.0")
}
}
val iosMain by creating {
dependencies {
implementation("io.ktor:ktor-client-darwin:3.0.0")
}
}
}
}

五、代码示例

1. 数据模型

1
2
3
4
import kotlinx.serialization.Serializable

@Serializable
data class User(val id: Int, val name: String)

2. HttpClient 初始化

1
2
3
4
5
6
7
8
9
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*

val httpClient = HttpClient {
install(ContentNegotiation) {
json()
}
}

3. 封装请求逻辑

1
2
3
4
5
6
import io.ktor.client.call.*
import io.ktor.client.request.*

suspend fun fetchUser(userId: Int): User {
return httpClient.get("https://api.example.com/users/$userId").body()
}

4. Repository 层

1
2
3
class UserRepository {
suspend fun getUser(userId: Int): User = fetchUser(userId)
}

5. ViewModel 层 (使用协程)

1
2
3
4
5
6
7
8
9
10
11
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class UserViewModel(private val repository: UserRepository) {
private val _user = MutableStateFlow<User?>(null)
val user: StateFlow<User?> = _user

suspend fun loadUser(id: Int) {
_user.value = repository.getUser(id)
}
}

六、平台调用

Android (Jetpack Compose)

1
2
3
4
5
6
7
8
9
10
11
12
13
class MainActivity : ComponentActivity() {
private val viewModel = UserViewModel(UserRepository())

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val user by viewModel.user.collectAsState()
LaunchedEffect(Unit) { viewModel.loadUser(123) }

Text(text = user?.name ?: "Loading...")
}
}
}

iOS (Swift)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import SwiftUI
import shared

struct ContentView: View {
var body: some View {
Text("Hello, World!")
.task {
do {
let user = try await UserRepository().getUser(userId: 123)
print(user.name)
} catch {
print("Error: \(error)")
}
}
}
}

七、进阶用法

  • 拦截器:日志、鉴权 Header 注入
  • WebSocket:即时通讯、推送
  • 多环境配置:BaseUrl 根据平台/构建类型切换
  • 与 SQLDelight 集成:实现离线缓存(Network + Local)

八、架构推荐

典型的 KMP + Ktor 数据层架构:

1
2
3
4
5
6
7
View (Compose / SwiftUI)

ViewModel (StateFlow + 协程)

Repository (调用 API + 数据库)

Ktor HttpClient (跨平台)

九、总结

  • KMP 提供跨平台逻辑共享能力
  • Ktor 作为跨平台网络框架,是数据层的核心实现
  • Android/iOS 都能直接调用,无需写两套请求逻辑
  • 推荐搭配:Ktor + kotlinx.serialization + SQLDelight + Koin,形成完整的数据层解决方案