Lingara Lingara Dokumentasie Gidse API Biblioteke Apps Bou Webtoepassing
Taal: Afrikaans

Kotlin

Hierdie bladsy is uit Engels vertaal. As die twee verskil, is die Engelse bladsy korrek. Lees die Engelse bladsy

Die Kotlin-biblioteek is com.getlingara:lingara-kotlin op Maven Central. Dit loop op die JVM, vereis Java 17 en Kotlin 2.2 of later, en gebruik kotlinx.coroutines en kotlinx.serialization.

Hoe dit lees

  • Elke oproep is ‘n suspend-funksie. Kanselleer die coroutine om die oproep te kanselleer, of gebruik withTimeout vir ‘n sperdatum; jy sien jou eie CancellationException, nooit ‘n toegedraaide een nie.
  • ‘n Stroom is ‘n EventStream, ‘n Flow wat jy een keer versamel. Versamel dit binne use, sodat dit sluit wanneer jy klaar is. Gebeurtenisse is data classes onder ‘n sealed interface, gepas met when.
  • Foute brei die sealed class LingaraException uit, so ‘n when daaroor is uitputtend. retryAfter is ‘n Duration, of null wanneer die API geen wagtyd genoem het nie.
  • Skep ‘n kliënt met die LingaraClient { }-bouer. Dit gebruik die JDK se HttpClient, wat jy met jou eie kan vervang.

Die voorbeelde hieronder voeg die afhanklikheid by, skep ‘n kliënt, stroom ‘n woordelys en hanteer ‘n fout.

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.

Wat hierdie bladsy omvou