简体   繁体   English

父挂起函数中的这些挂起函数会按顺序运行吗?

[英]Will these suspend functions inside in a parent suspend function be run in sequence?

The Code A is from the artical https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#3代码 A 来自文章https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#3

Will these suspend functions inside in a parent suspend function be run in sequence?父挂起函数中的这些挂起函数会按顺序运行吗?

The system run and get the result of val slow first, then run and get the result of val another , finally it run database.save(slow, another) , right ?系统先运行得到val slow的结果,然后运行得到val another的结果,最后运行database.save(slow, another) ,对吧?

Code A代码 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 { ... }

Yes, Kotlin suspending functions sequential by default .是的,Kotlin 默认按顺序挂起函数。

To run them in parallel you have to use async-await .要并行运行它们,您必须使用async-await

as document says...正如文件所说......

it is Sequential by default默认情况下是顺序的

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

you can do it Concurrent using async您可以使用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

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

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