[英]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@launch
, return@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.