当前位置:网站首页>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)耗时操作
边栏推荐
- [LeetCode]26. Removes duplicates from a sorted array thirty-three
- Druid reports an error connection holder is null
- Installation of IK word breaker
- Development notes of Mongoose
- Map from getting started to performance optimization
- [C] Inverts the binary of a decimal number and outputs it
- How to quickly query the mobile phone number home and operator
- Is the brokerage account in qiniu business school safe? Is the account opening rate low
- @Disallowcurrentexecution prevents quartz scheduled tasks from executing in parallel
- 分公司能与员工签劳动合同么
猜你喜欢

Tsinghua Bosch joint ml center, thbi lab:cheng Yang Ying | realize safety reinforcement learning through the value at risk of constraints
![[vscode]todo tree a to-do plug-in](/img/52/c977bc9cd021ca6fd12bcc22ae9f78.jpg)
[vscode]todo tree a to-do plug-in

Successfully installed opencv under delphixe

Cve-2021-24078 vulnerability analysis
![[buglist] serial port programming does not read data](/img/bf/8e63f679bf139fbbf222878792ae21.jpg)
[buglist] serial port programming does not read data

63. different paths II

On the parameters of main function in C language
![[MRCTF2020]Ez_bypass --BUUCTF](/img/73/85262c048e177968be67456fa4fe02.png)
[MRCTF2020]Ez_bypass --BUUCTF

The origin of MySQL in bedtime stories

Basics of network security (1)
随机推荐
MySQL locates the position of the character in the string String substitution
[GXYCTF2019]禁止套娃--详解
The difference between philosophy and Literature
Browser cache execution process
硬(磁)盘(一)
Leetcode weekly -- April to May
[LeetCode]28. Implement strstr()
TypeError: wave.ensureState is not a function
6.824 Lab 4B: Sharded Key/Value Service
Go custom collation
Druid reports an error connection holder is null
6.824 Lab 2: Raft
Pipelines in go concurrency mode
Arduino control tm1637 common positive four digit nixie tube
磁盘分区方式对比(MBR与GPT)
Card constructions -- two points
Target recognition gadget
Cve-2021-24078 vulnerability analysis
Converting Chinese numbers to Arabic numbers in Delphi
6.824 Lab 3A: Fault-tolerant Key/Value Service