Koltin协程-异步等待

时间:2018-10-03 09:15:53

标签: android kotlin kotlinx.coroutines

Roman Elizarov在有关Kotlin(https://medium.com/@elizarov/structured-concurrency-722d765aa952)中的结构化并发的文章中通过给出以下示例来解释并行分解:

coroutineScope { 
    val deferred1 = async { loadImage(name1) }
    val deferred2 = async { loadImage(name2) }
    combineImages(deferred1.await(), deferred2.await())
}

很显然,这段代码是不言自明的。但是,如果我们改为编写此代码,则会得到相同的结果

coroutineScope { 
    val result1 = async { loadImage(name1) }.await()
    val result2 = async { loadImage(name2) }.await()
    combineImages(result1, result2)
}

含义是,两个异步都会仍然并行运行,还是直到result1可用时第二次异步调用才会运行?

1 个答案:

答案 0 :(得分:4)

示例1:

fun main(args: Array<String>) = runBlocking<Unit> {
    val time = measureTimeMillis {
        val one = async {
            delay(1000)
            return@async 1
        }
        val two = async {
            delay(3000)
            return@async 2
        }
        println("The answer is ${one.await() + two.await()}")
    }
    println("Completed in $time ms")
}

结果1:

The answer is 3
Completed in 3041 ms

示例2:

fun main(args: Array<String>) = runBlocking<Unit> {
    val time = measureTimeMillis {
        val one = async {
            delay(1000)
            return@async 1
        }.await()
        val two = async {
            delay(3000)
            return@async 2
        }.await()
        println("The answer is ${one + two}")
    }
    println("Completed in $time ms")
}

结果2:

The answer is 3
Completed in 4043 ms

查看此链接以获取Concurrent using async的官方文档

结论

async-await-async-await将产生纯顺序代码

async-async-await-await将并行运行