一:使用场景:1.异步回调嵌套 2.并发流程控制
二:创建协程的常用方法
val job:Job = GlobalScope.launch (Dispatchers.Main){ }
val async:Deferred<Unit> = GlobalScope.async(Dispatchers.Main) { }
//Deferred其实就是Job的子类,实际上就是增加了个wait方法,能够让当前协程暂时挂起,暂停往下执行.当await方法有返回值后,会恢复协程往下执行
job.start()
job.join()//等待协程执行完毕
job.cancel()//取消协程
三:两种场景应用
a:三个异步方法执行,执行完后再更新UI
GlobalScope.launch (Dispatchers.Main){
val result1 = Request1()
val result2 = Request2(result1)
val result3 = Request3(result2)
updateUI(result3)
}
private fun updateUI(result: String){
Log.d("CoroutineScene","update work on ${Thread.currentThread().name}")
}
//suspend关键字的作用->
//delay它是io异步任务,是怎么样做到延迟协程中的代码向下执行的?
suspend fun Request1(): String{
delay(2*1000)
Log.d("CoroutineScene","request1 work on ${Thread.currentThread().name}")
return "result from request1"
}
suspend fun Request2(result: String): String{
delay(2*1000)
Log.d("CoroutineScene","request2 work on ${Thread.currentThread().name}")
return "result from request2"
}
suspend fun Request3(result: String): String{
delay(2*1000)
Log.d("CoroutineScene","request3 work on ${Thread.currentThread().name}")
return "result from request2"
}
b:创建一个方法,先执行request1后,再同时执行request2和request3
GlobalScope.launch(Dispatchers.Main) {
val result1 = Request1()
val deferred = GlobalScope.async { Request2(result1) }
val deferred1 = GlobalScope.async { Request3(result1) }
update(deferred.await(),deferred1.await())
}
//创建一个方法,先执行request1后,再同时执行request2和request3
private fun update(await: String, await1: String) {
}
四:协程挂起
被suspend关键字修饰的方法就可以看成挂起函数,当然不是只要suspend修饰了就能挂起,还要看内部实现,比如上面添加delay()这个异步方法,这种情况下就实现了函数挂起
从编译代码可以看出挂起的本质就是return & callback