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.
There is special syntax return@launch, return@async etc. depending on which scope you have launched
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.
val deferredValue = GlobalScope.async() { return@aysnc "hello world" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With