Kotlin
このページは英語から翻訳されています。内容に相違がある場合は、英語のページが正しい内容です。 英語のページを読む
Kotlin ライブラリは Maven Central の com.getlingara:lingara-kotlin です。JVM 上で動作し、Java 17 および Kotlin 2.2 以降が必要で、kotlinx.coroutines と kotlinx.serialization を使用します。
使い方
- すべての呼び出しは
suspend関数です。コルーチンをキャンセルすると呼び出しもキャンセルされます。期限を設けるにはwithTimeoutを使います。受け取るのは自分自身のCancellationExceptionであり、ラップされたものではありません。 - ストリームは
EventStreamで、一度だけ collect するFlowです。使い終わったら閉じられるよう、useの中で collect してください。イベントは sealed インターフェースの下にある data class で、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.