如何立即从范围内取消(return from)Kotlin协程?

How to cancel (return from) a Kotlin coroutine from within the scope immediately?

在以下代码中,我想在捕获到异常时停止执行此作用域。

GlobalScope.launch() {
   try {
       someFunctionThatThrows()
   } catch (exception: Exception) {
       // log
       cancel() // this is not stopping the coroutine and moreWork() is still executed
   }
   moreWork()
}

cancel() 不会立即取消协程,而是将标志 isActive 设置为 false,这需要后续检查。

有特殊语法 return@launchreturn@async 等,具体取决于您启动的范围

GlobalScope.launch() {
   try {
       someFunctionThatThrows()
   } catch (exception: Exception) {
       // log
       return@launch 
   }
   moreWork()
}

return@async 也可以有一个实际的 return 值传递给它的 Deferred<T> val.

val deferredValue = GlobalScope.async() { return@aysnc "hello world" }