

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Coroutines
<a name="coroutines"></a>

根據預設， 適用於 Kotlin 的 AWS SDK 是非同步的。適用於 Kotlin 的 SDK 對所有操作使用 `suspend`函數，這些函數旨在從 coroutine 呼叫。

如需 coroutine 的更深入指南，請參閱[官方 Kotlin 文件](https://kotlinlang.org/docs/coroutines-overview.html)。

## 提出並行請求
<a name="making-concurrent-requests"></a>

[非同步](https://kotlinlang.org/docs/composing-suspending-functions.html#concurrent-using-async) coroutine 建置器可用於啟動您關心結果的並行請求。 `async`會傳回[延遲](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html)，代表輕量、非封鎖的未來，代表稍後提供結果的承諾。

如果您不在意結果 （僅 操作已完成），您可以使用[啟動](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html) coroutine builder。 `launch` 概念上類似於 `async`。差別在於啟動會傳回[任務](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html)，且不會包含任何產生的值，而 會`async`傳回 `Deferred`。

以下是使用 [headObject](https://docs.aws.amazon.com/sdk-for-kotlin/api/latest/s3/aws.sdk.kotlin.services.s3/head-object.html) 操作向 Amazon S3 提出並行請求的範例，以取得兩個金鑰的內容大小：

```
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlin.system.measureTimeMillis
import aws.sdk.kotlin.services.s3.S3Client


fun main(): Unit = runBlocking {

    val s3 = S3Client { region = "us-east-2" }
    
    val myBucket = "<your-bucket-name-here>"
    val key1 = "<your-object-key-here>"
    val key2 = "<your-second-object-key-here>"

    val resp1 = async {
        s3.headObject{
            bucket = myBucket
            key = key1
        }
    }

    val resp2 = async {
        s3.headObject{
            bucket = myBucket
            key = key2
        }
    }


    val elapsed = measureTimeMillis {
        val totalContentSize = resp1.await().contentLength + resp2.await().contentLength
        println("content length of $key1 + $key2 = $totalContentSize")
    }

    println("requests completed in $elapsed ms")

}
```

## 提出封鎖請求
<a name="making-clocking-requests"></a>

若要從不使用 coroutine 的現有程式碼進行服務呼叫，並實作不同的執行緒模型，您可以使用 [runBlocking](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html) coroutine builder。不同執行緒模型的範例是使用 Java 的傳統執行器/未來方法。如果您要混合 Java 和 Kotlin 程式碼或程式庫，您可能需要使用此方法。

顧名思義，此`runBlocking`建置器會啟動新的 coroutine，並封鎖目前的執行緒，直到完成為止。

**警告**  
 `runBlocking` 通常不應從 coroutine 中使用。它旨在將一般封鎖程式碼橋接到以暫停樣式寫入的程式庫 （例如在主要函數和測試中）。