Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!