Kotlin 协程(Coroutine)是轻量级线程,让异步代码能以同步的方式编写,避免回调地狱。
suspend fun fetchUser(id: Int): User {
return withContext(Dispatchers.IO) {
repository.getUser(id)
}
}
suspend fun main() = coroutineScope {
val user = async { fetchUser(1) }
val posts = async { fetchPosts() }
println(user.await())
println(posts.await())
}
Flow 是 Kotlin 的响应式流,支持背压(backpressure)和结构化并发。
val numbers = flowOf(1, 2, 3)
numbers.onEach { println(it) }.launchIn(viewModelScope)