Bootstrap

Kotlin-协程

协程coroutine

什么是协程

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

协程的优点

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

引入协程

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1'

协程的创建

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

协程的使用

Dispatchers、async、suspend

suspend fun getInt():Int{
   
       Log.d(TAG,"getInt start ,Thread = ${Thread.currentThread().name}")
       delay(3000)
       Log.d(TAG,"getInt end ,Thread = ${Thread.currentThread().name}")
   
;