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

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

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 Relatório

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 Relatório

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 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