Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

462
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda