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

    }
相关推荐
佛系打工仔2 小时前
绘制K线第二章:背景网格绘制
android·前端·架构
my_power5205 小时前
车载安卓面试题汇总
android
csj505 小时前
安卓基础之《(15)—内容提供者(1)在应用之间共享数据》
android
yeziyfx6 小时前
kotlin中 ?:的用法
android·开发语言·kotlin
2501_915918417 小时前
只有 Flutter IPA 文件,通过多工具组合完成有效混淆与保护
android·flutter·ios·小程序·uni-app·iphone·webview
robotx7 小时前
AOSP 设置-提示音和振动 添加一个带有开关(Switch)的设置项
android
青莲8437 小时前
RecyclerView 完全指南
android·前端·面试
青莲8437 小时前
Android WebView 混合开发完整指南
android·前端·面试
龙之叶8 小时前
【Android Monkey源码解析三】- 运行解析
android
KevinWang_9 小时前
Android 的 assets 资源和 raw 资源有什么区别?
android