Kotlin 协程 supervisorScope {} 运行崩溃解决

前言

简单介绍supervisorScope函数,它用于创建一个使用了 SupervisorJob 的 coroutineScope,

该作用域的特点:抛出的异常,不会 连锁取消 同级协程和父协程。

看过很多 supervisorScope {} 文档的使用,我照抄一摸一样的代码,运行就崩溃,最后找到了解决方法,应该是kotlin版本更新做过改动,当前我使用的是 androidx.core:core-ktx:1.9.0

解决方法

需要将CoroutineExceptionHandler,作为参数,才有效果,不然会崩溃。

Kotlin 复制代码
    private fun test() {

        // 原来的写法,现在会崩溃
//        runBlocking {
//            Log.d("TAG", "Start")
//            launch {
//                delay(100)
//                Log.d("TAG", "Task from runBlocking")
//            }
//            supervisorScope {
//                val firstChild = launch {
//                    Log.d("TAG", "First Child")
//                    throw AssertionError("First child is cancelled")
//                }
//                val secondChild = launch {
//                    Log.d("TAG", "Second Child")
//                }
//                Log.d("TAG", "Cancelling supervisor")
//            }
//            Log.d("TAG", "End")
//        }


        // 最新的写法
        runBlocking {
            Log.d("TAG", "Start")
            launch {
                delay(100)
                Log.d("TAG", "Task from runBlocking")
            }
            supervisorScope {
                // 需要将CoroutineExceptionHandler,作为参数,才有效果,不然会崩溃
                val firstChild = launch(CoroutineExceptionHandler { _, _ -> }) {
                    Log.d("TAG", "First Child")
                    throw AssertionError("First child is cancelled")
                }
                val secondChild = launch {
                    Log.d("TAG", "Second Child")
                }
                Log.d("TAG", "Cancelling supervisor")
            }
            Log.d("TAG", "End")
        }

    }
相关推荐
leobertlan1 小时前
【好玩系列】训练一个神经网络指导小孩玩游戏
android·机器学习·程序员
Android-Flutter2 小时前
android LeakCanary 工作原理 详解
android·kotlin
AFinalStone3 小时前
Android 7系统无障碍服务(一)全景图与架构概览
android·无障碍服务
Android-Flutter3 小时前
android 自定义view 详解
android·kotlin
WAsbry3 小时前
协程任务的失败控制:取消、异常传播与Supervisor
android
Android打工仔4 小时前
从 finally 理解程序的控制流:它为什么不是 catch 后面的代码?
android·kotlin
随遇丿而安4 小时前
第15周:Service 全功能 + 后台优化
android
YXL1111YXL4 小时前
续体和状态机 —— suspend 函数的 CPS 变换
android·kotlin
WAsbry4 小时前
Flow数据模型:冷流、状态、事件与共享策略
android
WAsbry4 小时前
深入理解 Kotlin suspend:挂起语义、状态机与恢复调度
android