简体   繁体   English

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

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

In the following code I want to stop the execution of this scope when an exception was caught.在下面的代码中,我想在捕获异常时停止执行此范围。

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

cancel() does not cancel the coroutine immediately but instead sets the flag isActive to false, which requires subsequent checking. cancel()不会立即取消协程,而是将标志isActive为 false,这需要后续检查。

There is special syntax return@launch , return@async etc. depending on which scope you have launched有特殊的语法return@launchreturn@async等取决于您启动的范围

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

return@async can also have an actual return value that is passed into it's Deferred<T> val. return@async也可以有一个实际的返回值,它被传递到它的Deferred<T> val。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM