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 分钟前
使用 AI 进行科学调试
android·人工智能·kotlin
QING6181 小时前
Android Gradle Plugin 9.0 升级指南:告别十年技术债,你准备好了吗?
android·kotlin·gradle
Ehtan_Zheng1 小时前
内存泄漏检测:发现隐藏泄漏的工具
android
拭心1 小时前
Android 17 来了!新特性介绍与适配建议
android
Kapaseker2 小时前
一杯美式理解 Inner Class
android·kotlin
三少爷的鞋3 小时前
为什么 Google 不再推荐 SharedPreferences?答案其实只有一个:锁
android
JMchen1233 小时前
企业级图表组件库完整实现
android·java·经验分享·笔记·canvas·android-studio
草明11 小时前
android 蓝牙连接-兼容旧版本
android
鹏多多.11 小时前
Flutter使用screenshot进行截屏和截长图以及分享保存的全流程指南
android·前端·flutter·ios·前端框架
Flywith2414 小时前
【每日一技】Warp Workflow 使用示例
android·前端