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

258
Visualizações
Kotlin strange behaviour with chunked, async and await

I'm doing some code that involves a number of parallel requests in batchs from elements in a list and I'm facing a strange behaviour:

import kotlinx.coroutines.*

suspend fun main() {
    coroutineScope {
        val hello = listOf("hello", "world")
        val chunks = hello.chunked(1) {
            async { translate(it.first()) }
        }
        chunks.forEach {
            print(it.await())
        }
    }
}

private fun translate(word: String): String {
    return if(word == "hello") {
        "hola"
    } else {
        "mundo"
    }
}

It should display "holamundo" but sometimes this example prints "mundomundo" instead.

I made it available on Kotlin Playground as well.

What I'm missing here?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The reason for this behavior is that the code inside async is not run immediately. It is only scheduled. The async block returns before the lambda is invoked. This is why the it inside async block always points to the ["world"] window and hence the final output is "mundomundo".

Take this example:

fun main() {
    runBlocking {
        var a = 1
        val deferred = async {
            println(a)
        }
        a++
        deferred.await()
    }
}

Playground
In this example the output will be 2 and not 1 because a++ is processed before the async lambda.

Edit: As @IR42 pointed out in the comment, the documentation clearly mentions the the list passed to the transform function changes very quickly, so if you want to use it asynchronously you should first make a copy of it.

val chunks = hello.chunked(1) {
    val copy = it.toList()
    async { translate(copy.first()) }
}

This code will give you the expected output.

Another solution (thanks to @broot) is to first calculate the entire chunked list and then map it to the list of deferred.

val chunks = hello.chunked(1).map {
    async { translate(it.first()) }
}
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