Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

457
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda