学习网站 https://kaixue.io/kotlin-coroutines-1/
记录
Android
Add kotlinx-coroutines-android
module as dependency when using kotlinx.coroutines
on Android:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'
文档
https://www.kotlincn.net/docs/kotlin-docs.pdf
本质上,协程事轻量级的线程
基本使用
前面提到,launch
函数不是顶层函数,是不能直接用的,可以使用下面三种方法来创建协程:
🏝️
// 方法一,使用 runBlocking 顶层函数
runBlocking {
getImage(imageId)
}
// 方法二,使用 GlobalScope 单例对象
// 👇 可以直接调用 launch 开启协程
GlobalScope.launch {
getImage(imageId)
}
// 方法三,自行通过 CoroutineContext 创建一个 CoroutineScope 对象
// 👇 需要一个类型为 CoroutineContext 的参数
val coroutineScope = CoroutineScope(context)
coroutineScope.launch {
getImage(imageId)
}
Kotlin
- 方法一通常适用于单元测试的场景,而业务开发中不会用到这种方法,因为它是线程阻塞的。
- 方法二和使用
runBlocking
的区别在于不会阻塞线程。但在 Android 开发中同样不推荐这种用法,因为它的生命周期会和 app 一致,且不能取消(什么是协程的取消后面的文章会讲)。 - 方法三是比较推荐的使用方法,我们可以通过
context
参数去管理和控制协程的生命周期(这里的context
和 Android 里的不是一个东西,是一个更通用的概念,会有一个 Android 平台的封装来配合使用)。
🏝️
coroutineScope.launch(Dispatchers.Main) { // 👈 在 UI 线程开始
val image = withContext(Dispatchers.IO) { // 👈 切换到 IO 线程,并在执行完成后切回 UI 线程
getImage(imageId) // 👈 将会运行在 IO 线程
}
avatarIv.setImageBitmap(image) // 👈 回到 UI 线程更新 UI
}
练习题
- 开启一个协程,并在协程中打印出当前线程名。
- 通过协程下载一张网络图片并显示出来。
package com.tic.planb
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.tic.plan.Plan
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
val imgUrl =
"http://img1.gamersky.com/image2016/10/20161015_ls_141_5/gamersky_03origin_05_201610151947EAA.jpg"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(Dispatchers.Main).launch {
Log.d(TAG, "当前线程${Thread.currentThread().name}")
val bitmap = withContext(Dispatchers.IO) {
Log.d(TAG, "当前线程${Thread.currentThread().name}")
getImage(imgUrl)
}
mImageIv.setImageBitmap(bitmap)
}
}
private fun getImage(imgUrl: String): Bitmap {
val urlParam = URL(imgUrl)
val openConnection = urlParam.openConnection() as HttpURLConnection
openConnection.requestMethod = "GET"
openConnection.connect()
val inputStream = openConnection.inputStream
return BitmapFactory.decodeStream(inputStream)
}
}
记得开网络权限
Kotlin 协程的挂起好神奇好难懂?我今天把他的皮给扒了
-朱凯说的
接下来我们继续看看 async
是如何使用的,先回忆一下上期中获取头像的场景:
🏝️
coroutineScope.launch(Dispatchers.Main) {
// 👇 async 函数启动新的协程
val avatar: Deferred = async { api.getAvatar(user) } // 获取用户头像
val logo: Deferred = async { api.getCompanyLogo(user) } // 获取用户所在公司的 logo
// 👇 👇 获取返回值
show(avatar.await(), logo.await()) // 更新 UI
}
Kotlin
可以看到 avatar 和 logo 的类型可以声明为 Deferred
,通过 await
获取结果并且更新到 UI 上显示。
在了解了 suspend
关键字的来龙去脉之后,我们就可以进入下一个话题了:怎么自定义 suspend
函数。
这个「怎么自定义」其实分为两个问题:
- 什么时候需要自定义
suspend
函数? - 具体该怎么写呢?
什么时候需要自定义 suspend 函数
如果你的某个函数比较耗时,也就是要等的操作,那就把它写成 suspend
函数。这就是原则。
耗时操作一般分为两类:I/O 操作和 CPU 计算工作。比如文件的读写、网络交互、图片的模糊处理,都是耗时的,通通可以把它们写进 suspend
函数里。
另外这个「耗时」还有一种特殊情况,就是这件事本身做起来并不慢,但它需要等待,比如 5 秒钟之后再做这个操作。这种也是 suspend
函数的应用场景。
具体该怎么写
给函数加上 suspend
关键字,然后在 withContext
把函数的内容包住就可以了。
提到用 withContext
是因为它在挂起函数里功能最简单直接:把线程自动切走和切回。
当然并不是只有 withContext
这一个函数来辅助我们实现自定义的 suspend
函数,比如还有一个挂起函数叫 delay
,它的作用是等待一段时间后再继续往下执行代码。
使用它就可以实现刚才提到的等待类型的耗时操作:
🏝️
suspend fun suspendUntilDone() {
while (!done) {
delay(5)
}
}
Kotlin
这些东西,在我们初步使用协程的时候不用立马接触,可以先把协程最基本的方法和概念理清楚。
练习
使用协程下载一张图,并行进行两次切割
- 一次切成大小相同的 4 份,取其中的第一份
- 一次切成大小相同的 9 份,取其中的最后一份
得到结果后,将它们展示在两个 ImageView 上。
package com.tic.planb
import android.app.ProgressDialog.show
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.tic.plan.Plan
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.*
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
val imgUrl =
"http://img1.gamersky.com/image2016/10/20161015_ls_141_5/gamersky_03origin_05_201610151947EAA.jpg"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(Dispatchers.Main).launch {
Log.d(TAG, "当前线程${Thread.currentThread().name}")
val bitmap = getImage(imgUrl)
mImageIv.setImageBitmap(bitmap)
val bitmap1 = cropBitmap(bitmap, 0, 0, bitmap.width / 2, bitmap.height / 2)
mImageIv2.setImageBitmap(bitmap1)
val bitmap2 = cropBitmap(
bitmap,
bitmap.width * 2 / 3,
bitmap.height * 2 / 3,
bitmap.width / 3,
bitmap.height / 3
)
mImageIv3.setImageBitmap(bitmap2)
}
}
/**
* 下载图片,耗时
*/
private suspend fun getImage(imgUrl: String): Bitmap = withContext(Dispatchers.IO) {
Log.d(TAG, "当前线程${Thread.currentThread().name}")
val urlParam = URL(imgUrl)
val openConnection = urlParam.openConnection() as HttpURLConnection
openConnection.requestMethod = "GET"
openConnection.connect()
val inputStream = openConnection.inputStream
BitmapFactory.decodeStream(inputStream)
}
/**
* 切割图片
* @param source The bitmap we are subsetting
* @param x The x coordinate of the first pixel in source
* @param y The y coordinate of the first pixel in source
* @param width The number of pixels in each row
* @param height The number of rows
*/
private suspend fun cropBitmap(
source: Bitmap,
x: Int,
y: Int,
width: Int,
height: Int
): Bitmap = withContext(Dispatchers.IO) {
Bitmap.createBitmap(source, x, y, width, height)
}
}