CoroutineScope Dispatchers.IO异步操作async返回函数,Kotlin

CoroutineScope Dispatchers.IO异步操作async返回函数,Kotlin

Kotlin 复制代码
import kotlinx.coroutines.*

fun myFun(a: Int, b: Int, retFun: (sum: Int) -> Unit) {
    println("分支myFun开始... ${System.currentTimeMillis()}")
    val task = CoroutineScope(Dispatchers.IO).async(start = CoroutineStart.LAZY) {
        println("myFun delay... ${System.currentTimeMillis()}")
        delay(3000)
        println("myFun delay end ${System.currentTimeMillis()}")
        a + b
    }

    CoroutineScope(Dispatchers.IO).launch {
        println("myFun launch... ${System.currentTimeMillis()}")
        val sum = task.await()
        retFun(sum)
        println("myFun retFun ${System.currentTimeMillis()}")
    }
    println("分支myFun结束 ${System.currentTimeMillis()}")
}

fun main(args: Array<String>) {
    println("主流程开始 ... ${System.currentTimeMillis()}")
    myFun(1, 2) { sum ->
        println("主流程等待结果返回...")
        println("main : $sum ${System.currentTimeMillis()}")
        println("主流程结果返回")
    }
    println("主流程结束 ${System.currentTimeMillis()}")


    Thread.sleep(5000)
}

主流程开始 ... 1703757127994

分支myFun开始... 1703757127995

分支myFun结束 1703757128042

主流程结束 1703757128042

myFun launch... 1703757128045

myFun delay... 1703757128046

myFun delay end 1703757131050

主流程等待结果返回...

main : 3 1703757131052

主流程结果返回

myFun retFun 1703757131052

Process finished with exit code 0

相关推荐
alexhilton6 小时前
Compose中初始加载逻辑究竟应该放在哪里?
android·kotlin·android jetpack
zhangphil21 小时前
Android Coil3图片解码Bitmap后存入磁盘,再次加载读磁盘Bitmap缓存
android·kotlin
书中有颜如玉1 天前
Kotlin Coroutines 异步编程实战:从原理到生产级应用
android·开发语言·kotlin
Kapaseker2 天前
Kotlin 的 internal 修饰符到底咋回事儿?
android·kotlin
Trustport2 天前
ArcGIS Maps SDK For Kotlin 加载Layout中的MapView出错
android·开发语言·arcgis·kotlin
好家伙VCC2 天前
# ARCore+ Kotlin 实战:打造沉浸式增强现实交互应用在
java·python·kotlin·ar·交互
catoop3 天前
Kotlin 协程在 Android 开发中的应用:定义、优势与对比
android·kotlin
Lsk_Smion3 天前
Hot100(开刷) 之 环形链表(II)-- 随机链表的复制 -- 翻转二叉树
java·后端·kotlin·力扣·hot100
喂_balabala3 天前
Kotlin-属性委托
android·开发语言·kotlin
Kapaseker3 天前
介绍一个新的 Compose 控件 — 浮动菜单
android·kotlin