Lingara Lingara Tài liệu Cẩm nang API Thư viện Ứng dụng Tạo Ứng dụng web
Ngôn ngữ: Tiếng Việt

Kotlin

Trang này được dịch từ tiếng Anh. Nếu hai bản khác nhau, trang tiếng Anh là bản đúng. Đọc trang tiếng Anh

Thư viện Kotlin là com.getlingara:lingara-kotlin trên Maven Central. Thư viện chạy trên JVM, cần Java 17 và Kotlin 2.2 trở lên, và dùng kotlinx.coroutines cùng kotlinx.serialization.

Cách sử dụng

  • Mọi lệnh gọi đều là một hàm suspend. Hủy coroutine để hủy lệnh gọi, hoặc dùng withTimeout để đặt hạn chót; bạn sẽ thấy chính CancellationException của mình, không bao giờ là một ngoại lệ bị bọc lại.
  • Luồng là một EventStream, một Flow mà bạn thu thập một lần. Hãy thu thập nó bên trong use để nó được đóng khi bạn dùng xong. Các sự kiện là data class thuộc một sealed interface, được so khớp bằng when.
  • Các lỗi kế thừa sealed class LingaraException, nên một biểu thức when trên chúng sẽ bao quát mọi trường hợp. retryAfter là một Duration, hoặc null khi API không nêu thời gian chờ.
  • Tạo máy khách bằng trình dựng LingaraClient { }. Nó dùng HttpClient của JDK, và bạn có thể thay bằng máy khách của riêng mình.

Các mẫu dưới đây thêm phụ thuộc, tạo máy khách, phát trực tuyến một danh sách từ vựng và xử lý lỗi.

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.

Những gì trang này bao bọc