- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
第
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
文档评论(0)