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ùngwithTimeoutđể đặt hạn chót; bạn sẽ thấy chínhCancellationExceptioncủ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ộtFlowmà bạn thu thập một lần. Hãy thu thập nó bên tronguseđể 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ằngwhen. - Các lỗi kế thừa sealed class
LingaraException, nên một biểu thứcwhentrên chúng sẽ bao quát mọi trường hợp.retryAfterlà mộtDuration, hoặcnullkhi API không nêu thời gian chờ. - Tạo máy khách bằng trình dựng
LingaraClient { }. Nó dùngHttpClientcủ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.