第
Kotlin协程supervisorScope{}运行崩溃解决方法
目录Kotlin协程supervisorScope{}运行崩溃解决前言解决方法kotlin协程异常处理
Kotlin协程supervisorScope{}运行崩溃解决
前言
简单介绍supervisorScope函数,它用于创建一个使用了SupervisorJob的coroutineScope,
该作用域的特点:抛出的异常,不会连锁取消同级协程和父协程。
看过很多supervisorScope{}文档的使用,我照抄一摸一样的代码,运行就崩溃,最后找到了解决方法,应该是kotlin版本更新做过改动,当前我使用的是androidx.core:core-ktx:1.9.0
解决方法
需要将CoroutineExceptionHandler,作为参数,才有效果,不然会崩溃。
privatefuntest(){
//原来的写法,现在会崩溃
//runBlocking{
//Log.d(TAG,Start)
//launch{
//delay(100)
//Log.d(TAG,TaskfromrunBlocking)
//supervisorScope{
//valfirstChild=launch{
//Log.d(TAG,FirstChild)
//throwAssertionError(Firstchildiscancelled)
//valsecondChild=launch{
//Log.d(TAG,SecondChild)
//Log.d(TAG,Cancellingsupervisor)
//Log.d(TAG,End)
//最新的写法
runBlocking{
Log.d(TAG,Start)
launch{
delay(100)
Log.d(TAG,TaskfromrunBlocking)
supervisorScope{
//需要将CoroutineExceptionHandler,作为参数,才有效果,不然会崩溃
valfirstChild=launch(CoroutineExceptionHandler{_,_-}){
Log.d(TAG,FirstChild)
throwAssertionError(Firstchildiscancelled)
valsecondChild=launch{
Log.d(TAG,SecondChild)
Log.d(TAG,Cancellingsupervisor)
Log.d(TAG,End)
}
补充:
kotlin协程异常处理
importkotlinx.coroutines.*
import.URL
suspendfunfetchResponse(code:Int,delay:Int)=coroutineScope{
valdeferred:DeferredString=async{
URL(http://httpstat.us/$codesleep=$delay).readText()
try{
valresponse=deferred.await()
println(response)
}catch(ex:CancellationException){
println(${ex.message}forfetchResponse$code)
runBlocking{
valhandler=CoroutineExceptionHandler{_,ex-
println(exceptionhandled:${ex.message})
valjob=launch(Dispatchers.IO+SupervisorJob()+handler){
//协程1
launch{fetchResponse(202,1000)}//协程2
launch{fetchResponse(404,2000)}//协程3
launch{fetchResponse(200,3000)}//协程4
job.join()
}
如上的运行结果如下所示
202Accepted