Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 624
A1m Avatar asked Feb 02 '26 02:02

A1m


1 Answers

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" }

like image 188
A1m Avatar answered Feb 04 '26 14:02

A1m