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

    }
相关推荐
RATi GORI4 小时前
MySQL中的CASE WHEN语句:用法、示例与解析
android·数据库·mysql
MoFe14 小时前
【Mysql】创建IP授权用户并授权
android
冬奇Lab6 小时前
Camera2 API架构基础:Android视频系统的大门
android·音视频开发·源码阅读
hnlgzb6 小时前
安卓app kotlin语法,Hilt是什么东西?
android·开发语言·kotlin
Android系统攻城狮8 小时前
Android tinyalsa深度解析之pcm_params_get_periods_min调用流程与实战(一百七十三)
android·pcm·tinyalsa·音频进阶手册
Xempastissimo8 小时前
Android常见界面控件
android
法欧特斯卡雷特8 小时前
从 Kotlin 编译器 API 的变化开始: 2.3.20
android·后端·开源
词元Max10 小时前
1.5 Harness 架构深度解析:Claude Code 为什么强?
android·架构
yy552710 小时前
Mysql 主从复制与读写分离
android·数据库·mysql
zhenxin012211 小时前
万字详解 MySQL MGR 高可用集群搭建
android·mysql·adb