Lingara Lingara 說明文件 學習指南 API 函式庫 App 建立 網頁版
語言: 繁體中文

Kotlin

本頁譯自英文。如兩者有出入,以英文頁面為準。 閱讀英文頁面

Kotlin 函式庫是 Maven Central 上的 com.getlingara:lingara-kotlin。它在 JVM 上執行,需要 Java 17 和 Kotlin 2.2 或更新版本,並使用 kotlinx.coroutines 和 kotlinx.serialization。

使用方式

  • 每個呼叫都是 suspend 函式。取消協程即可取消呼叫,或是用 withTimeout 設定截止時間;你看到的是你自己的 CancellationException,絕不會是被包裝過的。
  • 串流是一個 EventStream,也就是只收集一次的 Flow。在 use 中收集它,這樣用完後它就會關閉。事件是密封介面下的資料類別,用 when 比對。
  • 錯誤繼承自密封類別 LingaraException,所以對它們的 when 是窮盡的。retryAfter 是一個 Duration,當 API 沒有指定等待時間時則為 null。
  • 用 LingaraClient { } 建構器建立用戶端。它使用 JDK 的 HttpClient,你可以把它換成自己的。

下面的範例會加入相依套件、建立用戶端、以串流方式取得詞彙清單並處理錯誤。

Kotlin

implementation("com.getlingara:lingara-kotlin:0.1.0-alpha.6")

Kotlin

import com.getlingara.kotlin.LingaraClient

val client =
    LingaraClient {
        clientCredentials(System.getenv("LINGARA_CLIENT_ID"), System.getenv("LINGARA_CLIENT_SECRET"))
    }

Kotlin

import com.getlingara.kotlin.LingaraClient
import com.getlingara.kotlin.model.GenerateVocabularyEvent
import com.getlingara.kotlin.model.VocabRequest

val request = VocabRequest(level = 2, sourceLang = "en", targetLang = "zh", count = 8)
// The request is sent here; collect the stream once, inside use {}.
client.generateVocabulary(request).use { stream ->
    stream.collect { event ->
        when (event) {
            is GenerateVocabularyEvent.Item -> println("${event.data.word} ${event.data.translation}")
            is GenerateVocabularyEvent.Started -> Unit
        }
    }
}

Kotlin

try {
    client.getUsage()
} catch (e: LingaraException) {
    when (e) {
        // A refusal from the API: status, code (stable) and message (localised).
        is ApiException -> println("${e.status} ${e.code} ${e.message}; retry after ${e.retryAfter}")
        // The token endpoint refused the credentials or the scopes.
        is OAuthException -> println("${e.status} ${e.error} ${e.description}")
        is MaintenanceException -> println("under maintenance; retry after ${e.retryAfter}")
        // No usable answer: CONNECT, TLS, RESET, TIMEOUT, and so on.
        is TransportException -> println("transport: ${e.kind}")
    }
}
// A cancelled call throws the caller's own CancellationException instead.

本頁封裝的內容