当前位置:网站首页>Kotlin 协程挂起函数 suspend 关键字
Kotlin 协程挂起函数 suspend 关键字
2022-06-13 00:36:00 【安果移不动】
suspend 挂起的是协程
协程是什么
就是launch{
}
or
async{
}
代码块中的东西
使用了suspend 后 就会切换出来一个协程去执行操作。而不是在当前的线程当中
suspend 是暂时切走。等执行完毕后再切回来。
launch(Dispatchers.Main) {
//切到子线程进行操作
val repoResponse: Response<FeedBackLists>
withContext(Dispatchers.IO) {
repoResponse = RetrofitClient
.instance
.getApi()
//suspend 挂起的方法必须在携程体内进行调用
.getFeedBack(1, 1)
}
//还是在主线程
binding.tvText.text = "repoResponse :${repoResponse.data!!.data[0].content}"
}
挂起可以理解为开个线程。或者是切个线程,只不过挂起这个函数执行完毕后,协程会自动切回到原先的那个线程。
所以所谓挂起。就是线程切换。这个切回来的操作
在线程当中叫做resume
但是suspend并没有切换线程。
首先自定义一个挂起函数
然后主线程调用
你会发现还是运行在主线程。
withContext可以切换到子线程
所以说suspend切换线程并不是发生在你外部这个挂起函数被调用的时候。而是withContext被调用的时候
withContext也没有直接切换线程。还在里面
在语法上面suspend关键字有什么用?
提醒,函数的创建者=》使用者的提醒
提醒这个是一个被自动放在后台运行的耗时函数。
这个提醒可以让主线程不卡
什么时候使用suspend关键字
耗时操作如 io、文件读写,网络交互,图片的模糊或者美化处理。
等待情况 如 deley(10000)耗时操作
边栏推荐
- 2022施工員-設備方向-通用基礎(施工員)操作證考試題及模擬考試
- Summary of openstack installation problems
- 人神共愤,唐山“群殴女性事件”细节...
- Is the brokerage account in qiniu business school safe? Is the account opening rate low
- Packaging and uplink of btcd transaction process (III)
- [GYCTF2020]Ezsqli --BUUCTF
- Go implements concurrent non blocking caching
- ROS2之OpenCV人脸识别foxy~galactic~humble
- 硬(磁)盘(二)
- Oceanbase is the leader in the magic quadrant of China's database in 2021
猜你喜欢
Daily buckle exercise - conclusion
测试平台系列(97) 完善执行case部分
Triangle wave and triangle wave convolution
1. Google grpc framework source code analysis Hello World
Use of split() method in string class
Mysql批量插入数据时如何解决重复问题?
[MRCTF2020]Ez_ bypass --BUUCTF
[vscode]todo tree a to-do plug-in
Static analysis of malicious code
[C] Inverts the binary of a decimal number and outputs it
随机推荐
浏览器控制台注入JS
Browser console injection JS
浏览器缓存的执行流程
A detailed explanation of synchronized
TypeError: wave. ensureState is not a function
[C] Inverts the binary of a decimal number and outputs it
C language standard IO, for example: fread(), fwrite(), fgetc(), etc. (end)
[GXYCTF2019]禁止套娃--详解
Building crud applications in golang
TypeError: wave.ensureState is not a function
Stm32f4 development of DMA transmission to GPIO port
Kali system -- host, dig, dnsenum, imtry for DNS collection and analysis
Kali system -- fierce of DNS collection and analysis
新增博客地址
测试平台系列(97) 完善执行case部分
MySQL finds duplicate data based on one or more fields
Win10 home vs pro vs enterprise vs enterprise LTSC
Can branches sign labor contracts with employees
通过抓包下载钉钉直播回放
MySQL query table field information