父暂挂函数中的这些暂挂函数是否将按顺序运行?

时间:2020-03-20 08:32:42

标签: kotlin kotlin-coroutines

代码A来自https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#3的文字

父暂挂函数中的这些暂挂函数是否将按顺序运行?

系统首先运行并获取val slow的结果,然后运行并获取val another的结果,最后它运行database.save(slow, another),对吗?

代码A

@WorkerThread
suspend fun makeNetworkRequest() {
    // slowFetch and anotherFetch are suspend functions
    val slow = slowFetch()
    val another = anotherFetch()
    // save is a regular function and will block this thread
    database.save(slow, another)
}

// slowFetch is main-safe using coroutines
suspend fun slowFetch(): SlowResult { ... }
// anotherFetch is main-safe using coroutines
suspend fun anotherFetch(): AnotherResult { ... }

2 个答案:

答案 0 :(得分:1)

是的,Kotlin暂停功能sequential by default

要并行运行它们,必须使用async-await

答案 1 :(得分:1)

如文件所述...

默认情况下它是顺序的

suspend fun taskOne(): Int {
    delay(1000L)
    return 5
}

suspend fun taskTwo(): Int {
    delay(1000L)
    return 5
}

val time = measureTimeMillis {
    val one = taskOne()
    val two = taskTwo()
    println("The total is ${one + two}")
}
println("time is $time ms")

//output
//The total is 10
//The total 2006 ms

您可以使用async

同时进行
suspend fun taskOne(): Int {
        delay(1000L)
        return 5
    }

    suspend fun taskTwo(): Int {
        delay(1000L)
        return 5
    }

    val time = measureTimeMillis {
        val one = async { taskOne() }
        val two = async { taskTwo() }
        println("The total is ${one.await() + two.await()}")
    }
    println("time is $time ms")

    //output
    //The total is 10
    //The total 1016 ms