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.
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()
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