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

    }
相关推荐
李艺为1 小时前
Android Studio使用switch匹配资源id时报需要常量表达式解决办法
android
YaBingSec3 小时前
玄机靶场-2024ccb初赛sc05 WP
android·运维·网络·笔记·安全·ssh
常利兵3 小时前
解锁Android嵌入式照片选择器,让你的App体验丝滑起飞
android
峥嵘life3 小时前
Android 切换用户后无法获取 MAC 地址分析解决
android·python·macos
JJay.3 小时前
Android BLE 为什么连上了却收不到数据
android
歪楼小能手3 小时前
Android16在开机向导最后添加一个声明界面
android·java·平板
夏沫琅琊3 小时前
Android联系人导入导出
android·kotlin
zh_xuan3 小时前
把Android Library 上传到github并在工程中引用该远程仓库
android·github·远程仓库
诸神黄昏EX3 小时前
Android Google MADA
android
盖丽男3 小时前
使用 GitHub Actions 自动打包 Android APK
android·github