协程:允许我们在单线程模式下模仿多线程编程效果
一:协程的基本用法
1.GlobalScope.launch{}(顶层协程)
delay()(非阻塞式的挂起函数)
2.runBlocking{} (测试环境使用) 会挂起外部线程
launch{} (创建多个子协程)
3.coroutinesScope {}(只能在协程作用域或者挂起挂起函数中调用)
suspend 关键字 (可以将任何函数声明成挂起函数)
launch {}(只能在协程作用域中调用)
挂起函数:
suspend fun printDot() = coroutinesScope{
launch{
println(".")
delay(1000)
}
}
协程作用域:
fun main{
funBlocking{
coroutinesScope{
launch{
for ( i in 1..10 ){
println(i)
delay(1000)
}
}
println("coroutinesScope finish")
}
println("funBlocking finish")
}
}
二:更多的作用域构建器
1. 作用域构建器:
(1).GlobalScope.launch{}
(2).runBlocking{}
(3).launch{}
(4).coroutinesScope{}
协程的取消:返回的Job对象,调用cancel ()
val job = GlobalScope.launch{
}
job.cancel()
2. CoroutinesScope:实际项目常用
val job = Job()
val scope = CoroutinesScope(job)
scope.launch{
}
job.cancel()
便于管理,同一作用域的所有协程全部取消
3.创建一个协程并获得它的执行结果 async{}.await()
fun main{
funBlocking{
val result = async{
5+5
}.await()
println(result)
}
}
注: async{}.await 是串行的,阻塞协程,为了执行效率,可以在最后获得结果的时候调用 await(),这样两个async{}函数就变成了并行关系了。
4.特殊的作用域构建器 withContext()
withContext(): 要求我们指定一个线程参数
1.Dispatchers.Default(低并发)
2.Dispatchers.IO(高并发)
3.Dispatchers.Main(主线程)
三:协程简化回调的写法
suspendCoroutine : 必须在协程作用域或者挂起函数中调用
resume()/resumeWithException() 协程恢复执行
例子:
suspend fun request(addr : String) : String {
return suspendCoroutine{continuation - >
HttpUtil.sendHttpRequest(addr, object : HttpCallBackListener{
override fun onFinish(response: String){
continuation.resume(response)
}
override fun onError(e: Exception){
continuation.resumeWithException(e)
}
})
}
}