Kotlin
이 페이지는 영어에서 번역되었습니다. 두 내용이 다를 경우 영어 페이지가 정확합니다. 영어 페이지 읽기
Kotlin 라이브러리는 Maven Central의 com.getlingara:lingara-kotlin입니다. JVM에서 실행되고, Java 17과 Kotlin 2.2 이상이 필요하며, kotlinx.coroutines와 kotlinx.serialization을 사용합니다.
사용 방식
- 모든 호출은
suspend함수입니다. 코루틴을 취소하면 호출이 취소되고, 기한을 두려면withTimeout을 사용하세요. 이때 보게 되는 것은 감싸진 예외가 아니라 여러분 자신의CancellationException입니다. - 스트림은
EventStream이며, 한 번만 수집하는Flow입니다. 다 쓰면 닫히도록use안에서 수집하세요. 이벤트는 sealed 인터페이스 아래의 데이터 클래스이며when으로 구분합니다. - 오류는 sealed 클래스
LingaraException을 확장하므로, 이를 대상으로 한when은 모든 경우를 빠짐없이 다룹니다.retryAfter는Duration이며, API가 대기 시간을 알려 주지 않았다면null입니다. - 클라이언트는
LingaraClient { }빌더로 만듭니다. JDK의HttpClient를 사용하며, 직접 만든 것으로 바꿀 수 있습니다.
아래 샘플은 의존성을 추가하고, 클라이언트를 만들고, 어휘 목록을 스트리밍하고, 오류를 처리합니다.
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.