场景一:如果有一个函数,它的返回值需要等到多个耗时的异步任务都执行完毕返回之后,组合所有任务的返回值作为 最终返回值
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
suspend fun asyncTask1(): String {
// 模拟异步任务1
kotlinx.coroutines.delay(1000)
return "Result from asyncTask1"
}
suspend fun asyncTask2(): String {
// 模拟异步任务2
kotlinx.coroutines.delay(1500)
return "Result from asyncTask2"
}
suspend fun asyncTask3(): String {
// 模拟异步任务3
kotlinx.coroutines.delay(2000)
return "Result from asyncTask3"
}
suspend fun performMultipleAsyncTasks(): List<String> = coroutineScope {
val deferredTask1 = async { asyncTask1() }
val deferredTask2 = async { asyncTask2() }
val deferredTask3 = async { asyncTask3() }
// 等待所有异步任务完成
val result = awaitAll(deferredTask1, deferredTask2, deferredTask3)
// 返回组合后的结果
result
}
fun main() = runBlocking {
val combinedResult = performMultipleAsyncTasks()
println("Combined Result: $combinedResult")
}
在上述示例中,asyncTask1
、asyncTask2
和asyncTask3
是模拟的异步任务。performMultipleAsyncTasks
函数使用async
启动了这些异步任务,并使用awaitAll
等待它们全部完成。最后,它将所有任务的结果组合成一个列表并返回。在main
函数中,使用runBlocking
启动协程来运行整个示例