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.