协程(Coroutine) 是一种轻量级的并发设计模式,可以在不阻塞线程的前提下挂起和恢复执行。Kotlin 的协程通过 suspend 函数和 CoroutineScope 实现结构化并发,特别适合 Android / Compose 中的异步任务。
| 对比维度 | 协程 (Coroutine) | 线程 (Thread) |
|---|---|---|
| 调度单位 | 用户态协作式调度 | 内核态抢占式调度 |
| 创建开销 | 极低(几 KB) | 较高(MB 级别栈) |
| 切换成本 | 函数调用级别(几乎无成本) | 上下文切换成本高 |
| 阻塞 vs 挂起 | 挂起不阻塞线程 | 阻塞会占用线程 |
| 并发数量 | 轻松支持数十万协程 | 通常数百个线程即瓶颈 |
| 代码可读性 | 顺序化异步(近似同步) | 回调/锁复杂 |
CoroutineScope 自动管理生命周期,避免泄漏。LaunchedEffect、rememberCoroutineScope 等完美集成。// 1. 使用 rememberCoroutineScope 启动协程
@Composable
fun GreetingScreen() {
val scope = rememberCoroutineScope()
var message by remember { mutableStateOf("加载中...") }
Button(onClick = {
scope.launch {
message = fetchData() // suspend 函数,不阻塞 UI
}
}) {
Text("获取数据")
}
Text(message)
}
// 2. LaunchedEffect:进入组合时自动启动协程
@Composable
fun UserProfile(userId: String) {
var profile by remember { mutableStateOf<Profile?>(null) }
LaunchedEffect(userId) {
profile = loadProfile(userId) // 挂起函数
}
// 显示 profile ...
}
✨ 协程核心优势总结
✅ 轻量 · 非阻塞 · 结构化 · 可取消 · 与 Compose 生命周期天然绑定 —— 让异步代码像同步一样简单。