Kotlin-协程

Kotlin-协程

  • 协程coroutine
    • 什么是协程
    • 协程的优点
    • 协程的创建
    • 协程的使用
    • 协程的挂起

协程coroutine

什么是协程

kotlin的协程可以理解为线程框架api,更好的处理多线程问题,可以在同一个代码块里进行多次的线程切换。一个线程可以开启多个协程,单个协程挂起后不会阻塞当前线程,线程还可以继续执行其他任务。

协程的优点

线程切换简单(这点和rxjava相似),并支持自动切回来,避免了回调嵌套,代码可读性高。

协程的创建

  1. 使用runBlocking顶层函数,线程阻塞的
runBlocking {
   getImage(imageId)
}
  1. 使用GlobalScope单例对象
GlobalScope.launch {
    getImage(imageId)
}
  1. 通过CoroutineContext创建一个CoroutineScope对象
val coroutineScope = CoroutineScope(context)
coroutineScope.launch {
   getImage(imageId)
}

协程的使用

Dispatchers、withContext、suspend

coroutineScope.launch(Dispatchers.Main) {      //在UI线程开始
   val image = suspendingGetImage(imageId)    //切换到IO线程,并在执行完成后切回UI线程
   avatarIv.setImageBitmap(image)             //回到UI线程更新 UI
} 

suspend fun suspendingGetImage(imageId: String){
   withContext(Dispatchers.IO){              //将会运行在IO线程
   	  getImage(imageId) 
   }
}

协程的挂起

suspend被称为非阻塞式挂起:
当某个协程执行到suspend函数,该协程会被挂起,直到suspend函数执行完,suspend函数执行完该协程就会自动恢复并继续执行,并自动切回到之前的线程

只能有两个地方允许使用suspend方法:
(1)在协程内部使用
(2)在另一个suspend方法里使用

你可能感兴趣的:(Android)