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

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

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启动协程来运行整个示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值