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.