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

144
Vistas
What is the type of an async result?

I'm trying to create some coroutines (async) in a loop . I want to start everything in parallel then wait for them all to finish before proceeding. The documentation provides the following example:

    coroutineScope {
        val deferreds = listOf(      // fetch two docs at the same time
            async { fetchDoc(1) },  // async returns a result for the first doc
            async { fetchDoc(2) }  // async returns a result for the second doc        
       deferreds.awaitAll()         // use awaitAll to wait for both network requests
    }

but this requires that all the class instantiations be known in advance. However with a varying number of instantiations this is not practical. As a work around I found that the following works: given a mutable List of class objects from class MyObject and MyObject has a method called myDo()

    private val mObjects = mutableListOf<MyObject>()

and ignoring error checking and assuming the list has 2 or more objects then the following works but it's kind of clunky and not very elegant

    coroutineScope {
    val pd = async { myObjects[0].myDo() }
    val dds = mutableListOf(pd)
        for (i in 1..numObjects - 1) {
                dds.add(async {mObjects[i].myDo() })
            }
            val nds = dds.toList()
            nds.awaitAll()
        }// end coroutineScope

What I'd hope to do was something like

    val dds = mutableListOf<Job>()
    for (i in 0..numObjects - 1) {
                dds.add(async {mObjects[i].myDo() })
           }
    val nds = dds.toList()
    nds.awaitAll()

but this doesn't work as the async result is a

    Deferred<out T> : Job

interface not a Job interface. The problem with this is in the line

    val dds = mutableListOf<Job>()

I don't know what to use in place of Job. That is, for async what is T?

Any help or suggestions would be appreciated

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

T in this case is whatever type myDo() returns.

I think you are overcomplicating it by creating the extra MutableLists. You can do it like this:

val results = coroutineScope {
    mObjects.map { obj ->
        async { obj.myDo() }
    }.awaitAll()
}

results will be a List<MyDoReturnType>.

Edit: I just realized, since it wasn't obvious to you that the type of a Deferred is whatever the async lambda returns, maybe it's because myDo() doesn't return anything (implicitly returns Unit). If that's the case, you should use launch instead of async. The only difference between them is that async's lambda returns something and launch's doesn't. Deferred inherits from Job because a Deferred is a Job with a result. If myDo() doesn't return anything, your code should look like the following, with no result.

coroutineScope {
    for (obj in mObjects) launch { obj.myDo() }
}
over 4 years ago · Santiago Trujillo Denunciar

0

The answer from TenFour04 provided the key to my answer The following code works for me

coroutineScope {
    val dds = mutableListOf<Deferred<Unit>>()
    for (item in mObjects) { dds.add(async {item.myDo() }) }
    val nds = dds.toList()
    nds.awaitAll()
}
over 4 years ago · Santiago Trujillo Denunciar

0

Am I stupid!!! or what. After I figured it out, the answer is almost trivial. The best solution I found is

private val mObjects = mutableListOf<MyObject>()

coroutineScope {val deferreds = listOf(mObjects.size){async{mObjects[it].myDo()}}
   deferreds.awaitAll()
}// end coroutineScope

I like this better than the map solution as it doesn't create an intermediate Pair set

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