簡體   English   中英

如何立即從范圍內取消(返回)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也可以有一個實際的返回值,它被傳遞到它的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