协程
suspend、Flow、结构化并发。
40 分钟
协程
Kotlin 协程是轻量级并发模型:suspend 函数可挂起不阻塞线程,Flow 处理异步数据流,结构化并发保证子任务生命周期可控。
学习目标
- 理解
suspend函数与协程的基本启动方式 - 掌握
async/await、Flow与collect - 了解结构化并发与
CoroutineScope
suspend 与 launch
import kotlinx.coroutines.*
suspend fun fetchLesson(slug: String): String {
delay(100) // 挂起,不阻塞线程
return "Lesson: $slug"
}
fun main() = runBlocking {
val job = launch {
val result = fetchLesson("kt-intro")
println(result)
}
job.join()
println("完成")
}
suspend 函数只能在协程或其他 suspend 函数中调用;delay 替代 Thread.sleep。
async 与并发
import kotlinx.coroutines.*
suspend fun fetchTitle(slug: String): String {
delay(50)
return slug.replace("-", " ").replaceFirstChar { it.uppercase() }
}
fun main() = runBlocking {
val slugs = listOf("kt-intro", "kt-syntax", "kt-control")
val deferred = slugs.map { slug ->
async { fetchTitle(slug) }
}
val titles = deferred.awaitAll()
println(titles)
}
async 返回 Deferred,await() 获取结果;适合并行 IO 或计算。
Flow 数据流
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun lessonFlow(): Flow<String> = flow {
listOf("kt-intro", "kt-syntax", "kt-control").forEach { slug ->
delay(30)
emit(slug)
}
}
fun main() = runBlocking {
lessonFlow()
.filter { it.startsWith("kt-") }
.map { it.uppercase() }
.collect { println(it) }
}
Flow 类似冷流,类似 RxJava / Java Stream 的 lazy 异步序列;collect 终端消费。
结构化并发
import kotlinx.coroutines.*
fun main() = runBlocking {
coroutineScope {
launch {
delay(200)
println("任务 A")
}
launch {
delay(100)
println("任务 B")
}
}
println("scope 内所有任务完成")
}
coroutineScope 等待所有子协程完成;父协程取消时子协程一并取消,避免泄漏。