Kotlin Coroutines(协程)使用笔记:可能会犯的 7 个错误

2023年 7月 12日 50.5k 0

Kotlin Coroutines(协程) 大大简化了同步和异步代码。但是,我发现了许多开发者在使用协程时会犯一些通用性的错误。

1. 在使用协程时实例化一个新的 Job 实例

有时候你会需要一个 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)
    ()
}

这段代码看起来没有任何问题,协程被成功取消了。

>_ 

performing some work in Coroutine
Coroutine was cancelled

Process finished with exit code 0

但是,让我们试试在协程作用域 CoroutineScope 中运行这个协程,然后取消协程作用域而不是协程的 job 。

fun main() = runBlocking {

    val scopeJob = Job()
    val scope = CoroutineScope(scopeJob)

    val coroutineJob = Job()
    (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)
    ()
}

当作用域被取消时,它内部的所有协程都会被取消。但是当我们再次执行修改过的代码时,情况并不是这样。

>_

performing some work in Coroutine

Process finished with exit code 0

现在,协程没有被取消,Coroutine was cancelled 没有被打印。

为什么会这样?

原来,为了让异步/同步代码更加安全,协程提供了革命性的特性 —— “结构化并发” 。“结构化并发” 的一个机制就是:当作用域被取消时,就取消该作用域中的所有协程。为了保证这一机制正常工作,作用域的 job 和协程的 job 之前的层级结构如下图所示:

Kotlin Coroutines(协程)使用笔记:可能会犯的 7 个错误

在我们的例子中,发生了一些异常情况。通过向协程构建器 launch() 传递我们自己的 job 实例,实际上并没有把新的 job 实例和协程本身进行绑定,取而代之的是,它成为了新协程的父 job。所以你创建的新协程的父 job 并不是协程作用域的 job,而是新创建的 job 对象。

因此,协程的 job 和协程作用域的 job 此时并没有什么关联。

Kotlin Coroutines(协程)使用笔记:可能会犯的 7 个错误

我们打破了结构化并发,因此当我们取消协程作用域时,协程将不再被取消。

解决方式是直接使用 launch() 返回的 job

fun main() = runBlocking {
    val scopeJob = Job()
    val scope = CoroutineScope(scopeJob)

    val coroutineJob =  {
        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)
    ()
}

这样,协程就可以随着作用域的取消而取消了。

>_

performing some work in Coroutine
Coroutine was cancelled

Process finished with exit code 0

2. 错误的使用 SupervisorJob

有时候你会使用 SupervisorJob 来达到下面的效果:

  • 在 job 继承体系中停止异常向上传播
  • 当一个协程失败时不影响其他的同级协程
  • 由于协程构建器 launch{} 和 async{} 都可以传递 Job 作为入参,所以你可以考虑向构建器传递 SupervisorJob 实例。

    launch(SupervisorJob()){
        // Coroutine Body
    }

    但是,就像错误 1 ,这样会打破结构化并发的取消机制。正确的解决方式是使用 supervisorScope{} 作用域函数。

    supervisorScope {
        launch {
            // Coroutine Body
        }
    }

    3. 不支持取消

    当你在自己定义的 suspend 函数中进行一些比较重的操作时,例如计算斐波拉契数列:

    // factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
    suspend fun calculateFactorialOf(number: Int): BigInteger =
        withContext() {
            var factorial = BigInteger.ONE
            for (i in 1..number) {
                factorial = ((()))
            }
            factorial
        }

    这个挂起函数有一个问题:它不支持 “合作式取消” 。这意味着即使执行这个函数的协程被提前取消了,它仍然会继续运行直到计算完成。为了避免这种情况,可以定期执行以下函数:

    • ensureActive()
    • isActive()
    • yield()

    下面的代码使用了 ensureActive()来支持取消。

    // factorial of n (n!) = 1 * 2 * 3 * 4 * ... * n
    suspend fun calculateFactorialOf(number: Int): BigInteger =
        withContext() {
            var factorial = BigInteger.ONE
            for (i in 1..number) {
                ensureActive()
                factorial = ((()))
            }
            factorial
        }

    Kotlin 标准库中的挂起函数(如 delay()) 都是可以配合取消的。但是对于你自己的挂起函数,不要忘记考虑取消的情况。

    4. 进行网络请求或者数据库查询时切换调度器

    这一项并不真的是一个 “错误” ,但是仍可能让你的代码难以理解,甚至更加低效。一些开发者认为当调用协程时,就应该切换到后台调度器,例如,进行网络请求的 Retrofit 的 suspend 函数,进行数据库操作的 Room 的 suspend 函数。

    这并不是必须的。因为所有的挂起函数都应该是主线程安全的,Retrofit 和 Room 都遵循了这一约定。

    5. 尝试使用 try/catch 来处理协程的异常

    协程的异常处理很复杂,我花了相当多的时间才完全理解。

    关于 Kotlin 协程异常处理最不直观的方面之一是,你不能使用 try-catch 来捕获异常。

    fun main() = runBlocking {
        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  。

    6. 在子协程中使用 CoroutineExceptionHandler

    再来一条简明扼要的:在子协程的构建器中使用 CoroutineExceptionHandler 不会有任何效果。这是因为异常处理是代理给父协程的。因为,你必须在根或者父协程或者 CoroutineScope 中使用 CoroutineExceptionHandler 。

    同样,更多细节请阅读  。

    7. 捕获 CancellationExceptions

    当协程被取消,正在执行的挂起函数会抛出 CancellationException 。这通常会导致协程发生 "异常" 并且立即停止运行。如下面代码所示:

    fun main() = runBlocking {
    
        val job = launch {
            println("Performing network request in Coroutine")
            delay(1000)
            println("Coroutine still running ... ")
        }
    
        delay(500)
        ()
    }

    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)
        ()
    }

    现在,假设服务端发生了 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)
        ()
    }

    或者再次抛出 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)
        ()
    }

    以上就是使用 Kotlin Coroutines 最常见的 7 个错误。如果你了解其他常见错误,欢迎在评论区留言!

    另外,不要忘记向其他开发者分享这篇文章以免发生这样的错误。

    相关文章

    JavaScript2024新功能:Object.groupBy、正则表达式v标志
    PHP trim 函数对多字节字符的使用和限制
    新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
    使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
    为React 19做准备:WordPress 6.6用户指南
    如何删除WordPress中的所有评论

    发布评论