Будут ли эти функции приостановки внутри родительской функции приостановки выполняться последовательно? - PullRequest
0 голосов
/ 20 марта 2020

Код А взят из художественного 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 ]

1 голос
/ 21 марта 2020

как сказано в документе ...

По умолчанию это последовательно

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
1 голос
/ 21 марта 2020

Да, Kotlin функции приостановки по умолчанию последовательно .

Для параллельного запуска их необходимо использовать asyn c -aait .

...