Junior — Middle
Kas async-i täitmine tühistatakse, kui selle sees on launch ja toimub erand?
sobes.tech AI
Vastus AI-lt
In Kotlin Coroutines, if within an async block a coroutine is started via launch, the exception occurring in launch will not automatically cancel the execution of async.
The reason is that async and launch create different coroutines with different error handling mechanisms:
asyncreturns aDeferred, and errors inside it will be propagated whenawait()is called.launchstarts a coroutine that does not return a result, and exceptions in it are handled viaCoroutineExceptionHandleror lead to cancellation of the parent coroutine.
If launch is started inside async without an explicit link to its Job, the exception in launch will not cancel async. To ensure cancellation, launch should be started in the same CoroutineScope or use SupervisorJob, or handle errors explicitly.
Example:
val deferred = async {
launch {
throw Exception("Error in launch")
}
// async execution continues
}
// Exception from launch will not affect `deferred` until `await()` is called