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.