Lingara Lingara 說明文件 學習指南 API 程式庫 App 建立 網頁版
語言: 粵語

Kotlin

呢頁係由英文翻譯過嚟嘅。如果兩個版本有出入,以英文頁為準。 睇英文頁

Kotlin 函式庫係 Maven Central 上面嘅 com.getlingara:lingara-kotlin。佢喺 JVM 上面行,要 Java 17 同 Kotlin 2.2 或者更新嘅版本,並且用 kotlinx.coroutines 同 kotlinx.serialization。

用起嚟點樣

  • 每個呼叫都係 suspend 函式。取消個協程就可以取消個呼叫,或者用 withTimeout 設個截止時間;你見到嘅係你自己嘅 CancellationException,永遠唔會係包過一層嘅。
  • 串流係一個 EventStream,即係一個只收集一次嘅 Flow。喺 use 入面收集佢,咁用完佢就會自己閂。事件係密封介面之下嘅資料類別,用 when 配對。
  • 錯誤繼承自密封類別 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.

呢頁包裝咗乜嘢