Kotlin
Esta página está traducida del inglés. Si ambas difieren, la página en inglés es la correcta. Leer la página en inglés
La biblioteca de Kotlin es com.getlingara:lingara-kotlin en Maven Central. Se ejecuta en la JVM, necesita Java 17 y Kotlin 2.2 o posterior, y usa kotlinx.coroutines y kotlinx.serialization.
Cómo se usa
- Cada llamada es una función
suspend. Cancela la corrutina para cancelar la llamada, o usawithTimeoutpara poner un plazo; verás tu propiaCancellationException, nunca una envuelta. - Un flujo es un
EventStream, unFlowque recolectas una sola vez. Recoléctalo dentro deuse, para que se cierre cuando termines. Los eventos son data classes bajo una interfaz sellada, que se distinguen conwhen. - Los errores extienden la clase sellada
LingaraException, así que unwhensobre ellos es exhaustivo.retryAfteres unaDuration, onullcuando la API no indicó ninguna espera. - Crea un cliente con el builder
LingaraClient { }. Usa elHttpClientdel JDK, que puedes sustituir por el tuyo.
Los ejemplos de abajo añaden la dependencia, crean un cliente, reciben en flujo una lista de vocabulario y gestionan un error.
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.