Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

459
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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()
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!