Kotlin
Esta página é uma tradução do inglês. Se as duas diferirem, a página em inglês é a correta. Ler a página em inglês
A biblioteca Kotlin é com.getlingara:lingara-kotlin no Maven Central. Corre na JVM, requer Java 17 e Kotlin 2.2 ou posterior, e usa kotlinx.coroutines e kotlinx.serialization.
Como se utiliza
- Cada chamada é uma função
suspend. Cancele a corrotina para cancelar a chamada, ou usewithTimeoutpara um prazo; vê a sua própriaCancellationException, nunca uma encapsulada. - Um stream é um
EventStream, umFlowque recolhe uma única vez. Recolha-o dentro deuse, para que se feche quando terminar. Os eventos são data classes sob uma interface selada, distinguidas comwhen. - Os erros estendem a classe selada
LingaraException, pelo que umwhensobre eles é exaustivo.retryAfteré umaDuration, ounullquando a API não indicou nenhuma espera. - Crie um cliente com o builder
LingaraClient { }. Usa oHttpClientdo JDK, que pode substituir pelo seu.
Os exemplos abaixo adicionam a dependência, criam um cliente, recebem em stream uma lista de vocabulário e tratam um erro.
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.