协程
基础概念
协程是轻量级线程,用于异步编程。
添加依赖
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
}
启动协程
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
delay(1000L)
println("World!")
}
println("Hello,")
}
协程构建器
launch
// 启动新协程,不返回结果
val job = GlobalScope.launch {
delay(1000L)
println("Task completed")
}
job.join() // 等待完成
async
// 启动协程并返回 Deferred
val deferred = GlobalScope.async {
delay(1000L)
"Result"
}
val result = deferred.await() // 获取结果
runBlocking
// 阻塞当前线程
runBlocking {
delay(1000L)
println("Done")
}
挂起函数
suspend fun fetchData(): String {
delay(1000L)
return "Data"
}
fun main() = runBlocking {
val data = fetchData()
println(data)
}
协程作用域
class MyClass {
private val scope = CoroutineScope(Dispatchers.Default)
fun doWork() {
scope.launch {
// 协程代码
}
}
fun cleanup() {
scope.cancel() // 取消所有协程
}
}
调度器
// 默认调度器
launch(Dispatchers.Default) {
// CPU 密集型任务
}
// IO 调度器
launch(Dispatchers.IO) {
// IO 操作
}
// 主线程调度器
launch(Dispatchers.Main) {
// UI 更新
}
// 无限制调度器
launch(Dispatchers.Unconfined) {
// 不限制线程
}
异常处理
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
val scope = CoroutineScope(Job() + handler)
scope.launch {
throw RuntimeException("Error")
}
并发
suspend fun fetchUser(): User = coroutineScope {
val profile = async { fetchProfile() }
val posts = async { fetchPosts() }
User(profile.await(), posts.await())
}
通道
val channel = Channel<Int>()
launch {
for (x in 1..5) {
channel.send(x * x)
}
channel.close()
}
launch {
for (y in channel) {
println(y)
}
}
Flow
fun numbers(): Flow<Int> = flow {
for (i in 1..3) {
delay(100)
emit(i)
}
}
fun main() = runBlocking {
numbers().collect { value ->
println(value)
}
}