Android kotlin 协程异步async与await介绍与使用

一、介绍

在kotlin语言中,协程是一个处理耗时的操作,但是很多人都知道同步和异步,但是不知道该如何正确的使用,如果处理不好,看似异步,其实在runBloacking模块中使用的结果是同步的。

针对如何同步和如何异步操作,接下来我会通过案例进行介绍

二、协程suspend

在kotlin中,如果方法被修饰了suspend,那么这个方法必须在协程中执行,常见的处理协程的有

复制代码
GlobalScope和runBlocking。

但是,单层的协程还是会由阻塞的情况

案例1.

Kotlin 复制代码
fun main() {
    println("start-------------")
    runBlocking {
        val text=GlobalScope.async { testLog("send") }
        println("text reslut=${text.await()}")

        println("text reslut mime")
    }
    println("end-------------")
}


suspend fun testLog(txt: String): String {

    delay(2500)
    return "back ${txt}"
}

结果还是按顺序执行了

案例2.

Kotlin 复制代码
fun main() {
    println("start-------------")

    GlobalScope.async {
        runBlocking {
            val text=GlobalScope.async { testLog("send") }
            println("text reslut=${text.await()}")

            println("text reslut mime")
        }
    }

    println("end-------------")
}


suspend fun testLog(txt: String): String {

    delay(2500)
    return "back ${txt}"
}

在runBlocking最外层加了一个异步的,结果runblocking没有执行。

案例3.

Kotlin 复制代码
fun main() {
    println("start-------------")


    runBlocking {
        val text = GlobalScope.async { testLog("send") }
        async {
            println("text reslut=${text.await()}")
        }

        println("text reslut mime")
    }


    println("end-------------")
}


suspend fun testLog(txt: String): String {

    delay(2500)
    return "back ${txt}"
}

结果:在runBlocking中,async{}模块中进行了等待,进行了异步数据返回。

案例4.

Kotlin 复制代码
fun main() {
    println("start-------------")


    runBlocking {

        async {
            println("text reslut 2500=${GlobalScope.async { testLog("send") }.await()}")
        }
        async {
            println("text reslut 1500=${GlobalScope.async { testLog("send",1500) }.await()}")
        }
        println("text reslut mime")
    }


    println("end-------------")
}


suspend fun testLog(txt: String,delays:Long=2500): String {

    delay(delays)
    return "back ${txt}"
}

结果:和我们设置的预期一致,耗时完顺手一致。

三、总结

通过以上几个案例,可以发现

1.异步如果不在runBlocking模块中进行,或者runBlocking模块外面再包一层,会引起最里面的模块,甚至方法体不在执行

2.想要异步执行,必须在runBlocking中对异步结果进行异步,否则达不到异步效果,变成了同步

3.整个函数的外面都是一个同步阻塞的,runBlocking一旦执行,下面的代码处于一个等待的状态

4.runBlocking中可以继续嵌套runBlocking异步执行模块。

相关推荐
奔跑吧 android2 小时前
【android bluetooth 协议分析 07】【SDP详解 2】【SDP 初始化】
android·bluetooth·aosp15·bt·gd·sdp_init
10年前端老司机3 小时前
React无限级菜单:一个项目带你突破技术瓶颈
前端·javascript·react.js
梦否4 小时前
Android 代码热度统计(概述)
android
阿芯爱编程7 小时前
2025前端面试题
前端·面试
xchenhao7 小时前
基于 Flutter 的开源文本 TTS 朗读器(支持 Windows/macOS/Android)
android·windows·flutter·macos·openai·tts·朗读器
前端小趴菜058 小时前
React - createPortal
前端·vue.js·react.js
coder_pig8 小时前
跟🤡杰哥一起学Flutter (三十五、玩转Flutter滑动机制📱)
android·flutter·harmonyos
晓13138 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
菜包eo9 小时前
如何设置直播间的观看门槛,让直播间安全有效地运行?
前端·安全·音视频
消失的旧时光-19439 小时前
OkHttp SSE 完整总结(最终版)
android·okhttp·okhttp sse