Lingara Lingara Docs Guides API Libraries Apps Build Web app
Language: English

Kotlin

The Kotlin library is com.getlingara:lingara-kotlin on Maven Central. It runs on the JVM, needs Java 17 and Kotlin 2.2 or later, and uses kotlinx.coroutines and kotlinx.serialization.

How it reads

  • Every call is a suspend function. Cancel the coroutine to cancel the call, or use withTimeout for a deadline; you see your own CancellationException, never a wrapped one.
  • A stream is an EventStream, a Flow you collect once. Collect it inside use, so it closes when you are done. Events are data classes under a sealed interface, matched with when.
  • Errors extend the sealed class LingaraException, so a when over them is exhaustive. retryAfter is a Duration, or null when the API named no wait.
  • Create a client with the LingaraClient { } builder. It uses the JDK’s HttpClient, which you can replace with your own.

The samples below add the dependency, create a client, stream a vocabulary list and handle an 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.

What this page wraps