Lingara Lingara ドキュメント 学習ガイド API ライブラリ アプリ 作成 ウェブ版
言語: 日本語

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.

このページがラップするもの