简体   繁体   English

Kotlin 分块、异步和等待的奇怪行为

[英]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:我正在做一些代码,这些代码涉及来自列表中元素的批量并行请求,我面临着一个奇怪的行为:

https://pl.kotl.in/joFkWgV13 https://pl.kotl.in/joFkWgV13

It should display "holamundo" but sometimes this example prints "mundomundo" instead.它应该显示“holamundo”,但有时这个示例会打印“mundomundo”。

What I'm missing here?我在这里缺少什么?

The reason for this behavior is that the code inside async is not run immediately.这种行为的原因是async内部的代码没有立即运行。 It is only scheduled.它只是预定的。 The async block returns before the lambda is invoked. async块在调用 lambda 之前返回。 This is why the it inside async block always points to the ["world"] window and hence the final output is "mundomundo".这就是为什么it inside async块总是指向["world"] window ,因此最终的 output 是 "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.在此示例中,output 将为2而不是1 ,因为a++async lambda 之前处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM