协程之实现一些“骚”操作

场景一:如果有一个函数,它的返回值需要等到多个耗时的异步任务都执行完毕返回之后,组合所有任务的返回值作为 最终返回值

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")
}

在上述示例中,asyncTask1asyncTask2asyncTask3是模拟的异步任务。performMultipleAsyncTasks函数使用async启动了这些异步任务,并使用awaitAll等待它们全部完成。最后,它将所有任务的结果组合成一个列表并返回。在main函数中,使用runBlocking启动协程来运行整个示例

猜你喜欢

转载自blog.csdn.net/Steve_XiaoHai/article/details/134332422