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

    }
相关推荐
柿蒂10 分钟前
从if-else和switch,聊聊“八股“的作用
android·java·kotlin
Jerry1 小时前
Compose 5 个简短动画,让您的应用脱颖而出
android
PenguinLetsGo2 小时前
你的App是否有出现过幽灵调用?
android
没有了遇见2 小时前
Android ViewPager2 嵌套 RecyclerView 滑动冲突解决方案
android
咖啡の猫3 小时前
Android开发-选择按钮
android·gitee
火柴就是我3 小时前
android 以maven的方式 引入本地的aar
android
过-眼-云-烟4 小时前
新版Android Studio能打包但无法run ‘app‘,编译通过后手机中没有安装,顶部一直转圈
android·ide·android studio
hedalei4 小时前
android14 硬键盘ESC改BACK按键返回无效问题
android·android14·esc·back按键
hcgeng5 小时前
android 如何判定底部导航栏显示时 不是键盘显示
android·底部导航·导航高度
和煦的春风5 小时前
性能案例分析 | Waiting for GPU completion
android·linux