Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions a list of deferred in Kotlin to get successful elements?

I have something like

listOf(
    getItem1Async(),
    getItem2Async(), //error
    getItem3Async()
).awaitAl
           

any of the functions could get an exception but because they return a deferred the exception is not handled until the await() call. I want for example if getItem2Async fails that my list creation doesn't fail but to get a default value or a null one and keep the successful calls.

I was looking into the documentation and couldn't figure out how to use the await on a list of deferred to return the items with no exception. I found something about a CoroutineExceptionHandler but cannot manage to return a null or default value, and also I read about a Supervisor job but I'm not sure if its the correct tool or if I sould use other one.

like image 287
Nicolas Vivas Avatar asked Oct 13 '25 07:10

Nicolas Vivas


1 Answers

First, we need to use supervisorScope(), so crashed child coroutines won't affect other coroutines. Then we can use Deferred.getCompleted(), Deferred.getCompletionExceptionOrNull() or similar functions to acquire a result:

suspend fun main() {
    supervisorScope {
        listOf(
            async { "hello" },
            async { check(false) },
            async { "world" },
        )
    }.map { it.getCompletedOrNull() }
        .forEach(::println)
}

@OptIn(ExperimentalCoroutinesApi::class)
fun <T> Deferred<T>.getCompletedOrNull() = if (isCancelled) null else getCompleted()
like image 158
broot Avatar answered Oct 15 '25 21:10

broot