Ansh Tyagi
02/03/2024, 9:20 AMMonoCoroutine was cancelled. Now i get it that when a coroutine is cancelled and we await, it will throw this JobCancellationExeception. For this i have done a standard try/catch method where i catch a CancellationException and it does not rethrow it. Now there are several reads i had over this topic. I want to have a public opinion on what are the best practices to handle this. Here is a code snippet:
val coroutineScope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
...
suspend func1() = withContext(coroutineScope.context) {
val deferredJob1 = async { someFunctionWhichCanThrowException() } // consider this throws an exception
val deferredJob2 = async { someFunction2WhichCanThrowException() }
val job1 = job1.await() // this will then throw a JobCancellationException
val job2 = job2.await()
}
...
now this await() i replaced it with safeAwait() which is basically a try/catch block.
My use case also have an awaitAll(), for which i have used .map{ safeAwait() } (ik its not optimised) thats why i wanna ask for a public opinion on whats the best practice to follow here?Sam
02/03/2024, 9:39 AMdeferredJob1 will propagate to the scope and cause the withContext block to fail with the same exception. If you do reach the call to job1.await(), any cancellation exception it throws will be ignored and the original exception is the one that will be thrown.Sam
02/03/2024, 9:39 AMAnsh Tyagi
02/03/2024, 9:49 AMAnsh Tyagi
02/03/2024, 10:01 AMsuspend fun func1() = mono { someAPI() }
suspend fun func2() = mono {
...
val job1 = func1.awaitSingle() // job cancellation exception
return ...
}Ansh Tyagi
02/03/2024, 10:02 AMAbdul Rizwan
02/07/2024, 3:42 AM