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

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

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