原文做者:Lukas Lechnerhtml
原文地址:7 common mistakes you might be making when using Kotlin Coroutinesjava
译者:秉心说git
在我看来,Kotlin Coroutines(协程) 大大简化了同步和异步代码。可是,我发现了许多开发者在使用协程时会犯一些通用性的错误。github
有时候你会须要一个 job
来对协程进行一些操做,例如,稍后取消。另外因为协程构建器 launch{}
和 async{}
都须要 job
做为入参,你可能会想到建立一个新的 job
实例做为参数来使用。这样的话,你就拥有了一个 job
引用,稍后你能够调用它的 .cancel()
方法。数据库
fun main() = runBlocking {
val coroutineJob = Job()
launch(coroutineJob) {
println("performing some work in Coroutine")
delay(100)
}.invokeOnCompletion { throwable ->
if (throwable is CancellationException) {
println("Coroutine was cancelled")
}
}
// cancel job while Coroutine performs work
delay(50)
coroutineJob.cancel()
}
复制代码
这段代码看起来没有任何问题,协程被成功取消了。安全
>_
performing some work in Coroutine
Coroutine was cancelled
Process finished with exit code 0
复制代码
可是,让咱们试试在协程做用域 CoroutineScope
中运行这个协程,而后取消协程做用域而不是协程的 job
。markdown
fun main() = runBlocking {
val scopeJob = Job()
val scope = CoroutineScope(scopeJob)
val coroutineJob = Job()
scope.launch(coroutineJob) {
println("performing some work in Coroutine")
delay(100)
}.invokeOnCompletion { throwable ->
if (throwable is CancellationException) {
println("Coroutine was cancelled")
}
}
// cancel scope while Coroutine performs work
delay(50)
scope.cancel()
}
复制代码
看成用域被取消时,它内部的全部协程都会被取消。可是当咱们再次执行修改过的代码时,状况并非这样。网络
>_
performing some work in Coroutine
Process finished with exit code 0
复制代码
如今,协程没有被取消,Coroutine was cancelled
没有被打印。并发
为何会这样?app
原来,为了让异步/同步代码更加安全,协程提供了革命性的特性 —— “结构化并发” 。“结构化并发” 的一个机制就是:看成用域被取消时,就取消该做用域中的全部协程。为了保证这一机制正常工做,做用域的 job
和协程的 job
以前的层级结构以下图所示:
在咱们的例子中,发生了一些异常状况。经过向协程构建器 launch()
传递咱们本身的 job
实例,实际上并无把新的 job
实例和协程自己进行绑定,取而代之的是,它成为了新协程的父 job
。因此你建立的新协程的父 job
并非协程做用域的 job
,而是新建立的 job
对象。
所以,协程的 job
和协程做用域的 job
此时并无什么关联。
咱们打破告终构化并发,所以当咱们取消协程做用域时,协程将再也不被取消。
解决方式是直接使用 launch()
返回的 job
。
fun main() = runBlocking {
val scopeJob = Job()
val scope = CoroutineScope(scopeJob)
val coroutineJob = scope.launch {
println("performing some work in Coroutine")
delay(100)
}.invokeOnCompletion { throwable ->
if (throwable is CancellationException) {
println("Coroutine was cancelled")
}
}
// cancel while coroutine performs work
delay(50)
scope.cancel()
}
复制代码
这样,协程就能够随着做用域的取消而取消了。
>_
performing some work in Coroutine
Coroutine was cancelled
Process finished with exit code 0
复制代码
有时候你会使用 SupervisorJob
来达到下面的效果:
因为协程构建器 launch{}
和 async{}
均可以传递 Job
做为入参,因此你能够考虑向构建器传递 SupervisorJob
实例。
launch(SupervisorJob()){
// Coroutine Body
}
复制代码
可是,就像错误 1 ,这样会打破结构化并发的取消机制。正确的解决方式是使用 supervisorScope{}
做用域函数。
supervisorScope {
launch {
// Coroutine Body
}
}
复制代码
当你在本身定义的 suspend
函数中进行一些比较重的操做时,例如计算斐波拉契数列:
// factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
suspend fun calculateFactorialOf(number: Int): BigInteger =
withContext(Dispatchers.Default) {
var factorial = BigInteger.ONE
for (i in 1..number) {
factorial = factorial.multiply(BigInteger.valueOf(i.toLong()))
}
factorial
}
复制代码
这个挂起函数有一个问题:它不支持 “合做式取消” 。这意味着即便执行这个函数的协程被提早取消了,它仍然会继续运行直到计算完成。为了不这种状况,能够按期执行如下函数:
下面的代码使用了 ensureActive() 来支持取消。
// factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
suspend fun calculateFactorialOf(number: Int): BigInteger =
withContext(Dispatchers.Default) {
var factorial = BigInteger.ONE
for (i in 1..number) {
ensureActive()
factorial = factorial.multiply(BigInteger.valueOf(i.toLong()))
}
factorial
}
复制代码
Kotlin 标准库中的挂起函数(如 delay()) 都是能够配合取消的。可是对于你本身的挂起函数,不要忘记考虑取消的状况。
这一项并不真的是一个 “错误” ,可是仍可能让你的代码难以理解,甚至更加低效。一些开发者认为当调用协程时,就应该切换到后台调度器,例如,进行网络请求的 Retrofit 的 suspend
函数,进行数据库操做的 Room 的 suspend
函数。
这并非必须的。由于全部的挂起函数都应该是主线程安全的,Retrofit 和 Room 都遵循了这一约定。你能够阅读个人 这篇文章 以了解更多内容。
协程的异常处理很复杂,我花了至关多的时间才彻底理解,并经过 博客 和 讲座 向其余开发者进行了解释。我还做了一些 图 来总结这个复杂的话题。
关于 Kotlin 协程异常处理最不直观的方面之一是,你不能使用 try-catch
来捕获异常。
fun main() = runBlocking<Unit> {
try {
launch {
throw Exception()
}
} catch (exception: Exception) {
println("Handled $exception")
}
}
复制代码
若是运行上面的代码,异常不会被处理而且应用会 crash 。
>_
Exception in thread "main" java.lang.Exception
Process finished with exit code 1
复制代码
Kotlin Coroutines 让咱们能够用传统的编码方式书写异步代码。可是,在异常处理方面,并无如大多数开发者想的那样使用传统的 try-catch
机制。若是你想处理异常,在协程内直接使用 try-catch
或者使用 CoroutineExceptionHandler
。
更多信息能够阅读前面提到的这篇 文章 。
再来一条简明扼要的:在子协程的构建器中使用 CoroutineExceptionHandler
不会有任何效果。这是由于异常处理是代理给父协程的。由于,你必须在根或者父协程或者 CoroutineScope
中使用 CoroutineExceptionHandler
。
一样,更多细节请阅读 这里 。
当协程被取消,正在执行的挂起函数会抛出 CancellationException
。这一般会致使协程发生 "异常" 而且当即中止运行。以下面代码所示:
fun main() = runBlocking {
val job = launch {
println("Performing network request in Coroutine")
delay(1000)
println("Coroutine still running ... ")
}
delay(500)
job.cancel()
}
复制代码
500 ms 以后,挂起函数 delay()
抛出了 CancellationException
,协程 "异常结束" 而且中止运行。
>_
Performing network request in Coroutine
Process finished with exit code 0
复制代码
如今让咱们假设 delay()
表明一个网络请求,为了处理网络请求可能发生的异常,咱们用 try-catch
代码块来捕获全部异常。
fun main() = runBlocking {
val job = launch {
try {
println("Performing network request in Coroutine")
delay(1000)
} catch (e: Exception) {
println("Handled exception in Coroutine")
}
println("Coroutine still running ... ")
}
delay(500)
job.cancel()
}
复制代码
如今,假设服务端发生了 bug 。catch
分支不只会捕获错误网络请求的 HttpException
,对于 CancellationExceptions
也是。所以协程不会 “异常中止”,而是继续运行。
>_
Performing network request in Coroutine
Handled exception in Coroutine
Coroutine still running ...
Process finished with exit code 0
复制代码
这可能致使设备资源浪费,甚至在某些状况下致使崩溃。
要解决这个问题,咱们能够只捕获 HttpException
。
fun main() = runBlocking {
val job = launch {
try {
println("Performing network request in Coroutine")
delay(1000)
} catch (e: HttpException) {
println("Handled exception in Coroutine")
}
println("Coroutine still running ... ")
}
delay(500)
job.cancel()
}
复制代码
或者再次抛出 CancellationExceptions
。
fun main() = runBlocking {
val job = launch {
try {
println("Performing network request in Coroutine")
delay(1000)
} catch (e: Exception) {
if (e is CancellationException) {
throw e
}
println("Handled exception in Coroutine")
}
println("Coroutine still running ... ")
}
delay(500)
job.cancel()
}
复制代码
以上就是使用 Kotlin Coroutines 最多见的 7 个错误。若是你了解其余常见错误,欢迎在评论区留言!
另外,不要忘记向其余开发者分享这篇文章以避免发生这样的错误。Thanks !
Thank you for reading, and have a great day!