首页 > 解决方案 > 此处不允许“返回”:Kotlin Coroutine 启动(UI)块

问题描述

fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res!=null){
            fetchCatalog(context!!)
            catalogActivityCatalog?.refresh()
        }
    }
}

上面的代码工作正常。我想通过返回(从而停止执行) if 来避免 if 中的嵌套部分res == null,就像这样,

fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res==null)return                  //this line changed <---A

        fetchCatalog(context!!)              //moved outside if block
        catalogActivityCatalog?.refresh()    //moved outside if block
    }
}

当我在 <--A 指示的行中使用 return 时,它说这里不允许“return”

这里有退出launch块的关键字吗?什么是可以在这里使用而不是返回的替代方法?

标签: kotlinkotlin-android-extensionskotlinx.coroutines

解决方案


必须使用指定返回的目的地return@...

fun onYesClicked(view: View) {

    launch(UI) {
        val res = post(context!!,"deleteRepo")

        if(res==null)return@launch     //return at launch

        fetchCatalog(context!!)              
        catalogActivityCatalog?.refresh()    
    }
}

推荐阅读