<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                **目錄** [TOC] ## 組合掛起函數 本節介紹了將掛起函數組合的各種方法。 ### 默認順序調用 假設我們在不同的地方定義了兩個進行某種調用遠程服務或者進行計算的掛起函數。我們只假設它們都是有用的,但是實際上它們在這個示例中只是為了該目的而延遲了一秒鐘: ```kotlin suspend fun doSomethingUsefulOne(): Int { delay(1000L) // 假設我們在這里做了一些有用的事 return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // 假設我們在這里也做了一些有用的事 return 29 } ``` 如果需要按 _順序_ 調用它們,我們接下來會做什么——首先調用 `doSomethingUsefulOne` _接下來_調用 `doSomethingUsefulTwo`,并且計算它們結果的和嗎?實際上,如果我們要根據第一個函數的結果來決定是否我們需要調用第二個函數或者決定如何調用它時,我們就會這樣做。 我們使用普通的順序來進行調用,因為這些代碼是運行在協程中的,只要像常規的代碼一樣 _順序_ 都是默認的。下面的示例展示了測量執行兩個掛起函數所需要的總時間: ```kotlin import kotlinx.coroutines.* import kotlin.system.* fun main() = runBlocking<Unit> { //sampleStart val time = measureTimeMillis { val one = doSomethingUsefulOne() val two = doSomethingUsefulTwo() println("The answer is ${one + two}") } println("Completed in $time ms") //sampleEnd } suspend fun doSomethingUsefulOne(): Int { delay(1000L) // 假設我們在這里做了些有用的事 return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // 假設我們在這里也做了一些有用的事 return 29 } ``` > 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-compose-01.kt)獲取完整代碼。 它的打印輸出如下: ```text The answer is 42 Completed in 2017 ms ``` ### 使用 async 并發 如果 `doSomethingUsefulOne` 與 `doSomethingUsefulTwo` 之間沒有依賴,并且我們想更快的得到結果,讓它們進行 _并發_ 嗎?這就是 [async](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html) 可以幫助我們的地方。 在概念上,[async](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html) 就類似于 [launch](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html)。它啟動了一個單獨的協程,這是一個輕量級的線程并與其它所有的協程一起并發的工作。不同之處在于 `launch` 返回一個 [Job](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html) 并且不附帶任何結果值,而 `async` 返回一個 [Deferred](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html) —— 一個輕量級的非阻塞 future,這代表了一個將會在稍后提供結果的 promise。你可以使用 `.await()` 在一個延期的值上得到它的最終結果,但是 `Deferred` 也是一個 `Job`,所以如果需要的話,你可以取消它。 ```kotlin import kotlinx.coroutines.* import kotlin.system.* fun main() = runBlocking<Unit> { //sampleStart val time = measureTimeMillis { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } println("The answer is ${one.await() + two.await()}") } println("Completed in $time ms") //sampleEnd } suspend fun doSomethingUsefulOne(): Int { delay(1000L) // 假設我們在這里做了些有用的事 return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // 假設我們在這里也做了些有用的事 return 29 } ``` > 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-compose-02.kt)獲取完整代碼。 它的打印輸出如下: ```text The answer is 42 Completed in 1017 ms ``` 這里快了兩倍,因為兩個協程并發執行。請注意,使用協程進行并發總是顯式的。 ### 惰性啟動的 async 可選的,[async](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html) 可以通過將 `start` 參數設置為 [CoroutineStart.LAZY](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/-l-a-z-y.html) 而變為惰性的。在這個模式下,只有結果通過 [await](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html)獲取的時候協程才會啟動,或者在 `Job` 的 [start](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/start.html)函數調用的時候。運行下面的示例: ```kotlin import kotlinx.coroutines.* import kotlin.system.* fun main() = runBlocking<Unit> { //sampleStart val time = measureTimeMillis { val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() } val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() } // 執行一些計算 one.start() // 啟動第一個 two.start() // 啟動第二個 println("The answer is ${one.await() + two.await()}") } println("Completed in $time ms") //sampleEnd } suspend fun doSomethingUsefulOne(): Int { delay(1000L) // 假設我們在這里做了些有用的事 return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // 假設我們在這里也做了些有用的事 return 29 } ``` > 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-compose-03.kt)獲取完整代碼。 它的打印輸出如下: ```text The answer is 42 Completed in 1017 ms ``` 因此,在先前的例子中這里定義的兩個協程沒有執行,但是控制權在于程序員準確的在開始執行時調用 [start](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/start.html)。我們首先調用 `one`,然后調用 `two`,接下來等待這個協程執行完畢。 注意,如果我們只是在 `println` 中調用 [await](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html),而沒有在單獨的協程中調用 [start](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/start.html),這將會導致順序行為,直到 [await](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html)啟動該協程執行并等待至它結束,這并不是惰性的預期用例。在計算一個值涉及掛起函數時,這個 `async(start = CoroutineStart.LAZY)` 的用例用于替代標準庫中的 `lazy` 函數。 ### async 風格的函數 我們可以定義異步風格的函數來 _異步_ 的調用 `doSomethingUsefulOne` 和 `doSomethingUsefulTwo`并使用 [async](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html) 協程建造器并帶有一個顯式的 [GlobalScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html) 引用。我們給這樣的函數的名稱中加上“……Async”后綴來突出表明:事實上,它們只做異步計算并且需要使用延期的值來獲得結果。 ```kotlin // somethingUsefulOneAsync 函數的返回值類型是 Deferred<Int> fun somethingUsefulOneAsync() = GlobalScope.async { doSomethingUsefulOne() } // somethingUsefulTwoAsync 函數的返回值類型是 Deferred<Int> fun somethingUsefulTwoAsync() = GlobalScope.async { doSomethingUsefulTwo() } ``` 注意,這些 `xxxAsync` 函數**不是** _掛起_ 函數。它們可以在任何地方使用。然而,它們總是在調用它們的代碼中意味著異步(這里的意思是 _并發_ )執行。 下面的例子展示了它們在協程的外面是如何使用的: ```kotlin import kotlinx.coroutines.* import kotlin.system.* //sampleStart // 注意,在這個示例中我們在 `main` 函數的右邊沒有加上 `runBlocking` fun main() { val time = measureTimeMillis { // 我們可以在協程外面啟動異步執行 val one = somethingUsefulOneAsync() val two = somethingUsefulTwoAsync() // 但是等待結果必須調用其它的掛起或者阻塞 // 當我們等待結果的時候,這里我們使用 `runBlocking { …… }` 來阻塞主線程 runBlocking { println("The answer is ${one.await() + two.await()}") } } println("Completed in $time ms") } //sampleEnd fun somethingUsefulOneAsync() = GlobalScope.async { doSomethingUsefulOne() } fun somethingUsefulTwoAsync() = GlobalScope.async { doSomethingUsefulTwo() } suspend fun doSomethingUsefulOne(): Int { delay(1000L) // 假設我們在這里做了些有用的事 return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // 假設我們在這里也做了些有用的事 return 29 } ``` > 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-compose-04.kt)獲取完整代碼。 ``` The answer is 42 Completed in 1085 ms ``` > 這種帶有異步函數的編程風格僅供參考,因為這在其它編程語言中是一種受歡迎的風格。在 Kotlin 的協程中使用這種風格是**強烈不推薦**的,原因如下所述。 考慮一下如果 `val one = somethingUsefulOneAsync()` 這一行和 `one.await()` 表達式這里在代碼中有邏輯錯誤, 并且程序拋出了異常以及程序在操作的過程中中止,將會發生什么。通常情況下,一個全局的異常處理者會捕獲這個異常,將異常打印成日記并報告給開發者,但是反之該程序將會繼續執行其它操作。但是這里我們的`somethingUsefulOneAsync` 仍然在后臺執行,盡管如此,啟動它的那次操作也會被終止。這個程序將不會進行結構化并發,如下一小節所示。 ### 使用 async 的結構化并發 讓我們使用[使用 async 的并發](http://www.kotlincn.net/docs/reference/coroutines/composing-suspending-functions.html#%E4%BD%BF%E7%94%A8-async-%E7%9A%84%E7%BB%93%E6%9E%84%E5%8C%96%E5%B9%B6%E5%8F%91)這一小節的例子并且提取出一個函數并發的調用 `doSomethingUsefulOne` 與 `doSomethingUsefulTwo` 并且返回它們兩個的結果之和。 由于 [async](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html) 被定義為了 [CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html) 上的擴展,我們需要將它寫在作用域內,并且這是 [coroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html) 函數所提供的: ```kotlin suspend fun concurrentSum(): Int = coroutineScope { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } one.await() + two.await() } ``` 這種情況下,如果在 `concurrentSum` 函數內部發生了錯誤,并且它拋出了一個異常,所有在作用域中啟動的協程都會被取消。 ```kotlin import kotlinx.coroutines.* import kotlin.system.* fun main() = runBlocking<Unit> { //sampleStart val time = measureTimeMillis { println("The answer is ${concurrentSum()}") } println("Completed in $time ms") //sampleEnd } suspend fun concurrentSum(): Int = coroutineScope { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } one.await() + two.await() } suspend fun doSomethingUsefulOne(): Int { delay(1000L) // 假設我們在這里做了些有用的事 return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // 假設我們在這里也做了些有用的事 return 29 } ``` > 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-compose-05.kt)獲取完整代碼。 從上面的 `main` 函數的輸出可以看出,我們仍然可以同時執行這兩個操作: ```text The answer is 42 Completed in 1017 ms ``` 取消始終通過協程的層次結構來進行傳遞: ```kotlin import kotlinx.coroutines.* fun main() = runBlocking<Unit> { try { failedConcurrentSum() } catch(e: ArithmeticException) { println("Computation failed with ArithmeticException") } } suspend fun failedConcurrentSum(): Int = coroutineScope { val one = async<Int> { try { delay(Long.MAX_VALUE) // 模擬一個長時間的運算 42 } finally { println("First child was cancelled") } } val two = async<Int> { println("Second child throws an exception") throw ArithmeticException() } one.await() + two.await() } ``` > 可以在[這里](https://github.com/hltj/kotlinx.coroutines-cn/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-compose-06.kt)獲取完整代碼。 請注意,如果其中一個子協程(即 `two`)失敗,第一個 `async` 以及等待中的父協程都會被取消: ```text Second child throws an exception First child was cancelled Computation failed with ArithmeticException ``` [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html [Deferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html [CoroutineStart.LAZY]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-start/-l-a-z-y.html [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html [Job.start]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/start.html [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html [coroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看