Lingara Lingara المستندات أدلة التعلّم API المكتبات التطبيقات البناء تطبيق الويب
اللغة: العربية

Kotlin

هذه الصفحة مترجمة من الإنجليزية. إذا اختلفت النسختان، فالصفحة الإنجليزية هي الصحيحة. اقرأ الصفحة الإنجليزية

مكتبة Kotlin هي com.getlingara:lingara-kotlin على Maven Central. تعمل على JVM، وتحتاج إلى Java 17 وKotlin 2.2 أو أحدث، وتستخدم kotlinx.coroutines وkotlinx.serialization.

كيف تبدو في الاستخدام

  • كل استدعاء دالة suspend. ألغِ الروتين المشترك لإلغاء الاستدعاء، أو استخدم withTimeout لتحديد موعد نهائي؛ سترى CancellationException الخاص بك، لا نسخة مغلّفة منه أبدًا.
  • التدفق هو EventStream، وهو Flow تجمعه مرة واحدة. اجمعه داخل use، ليُغلق عند انتهائك. الأحداث فئات بيانات تحت واجهة مختومة، تُطابَق باستخدام when.
  • ترث الأخطاء من الفئة المختومة LingaraException، لذا فإن when عليها شامل. تكون retryAfter من النوع Duration، أو null عندما لا يحدد الـ API مدة انتظار.
  • أنشئ عميلًا باستخدام المُنشئ LingaraClient { }. يستخدم HttpClient الخاص بـ JDK، ويمكنك استبداله بعميلك الخاص.

تضيف الأمثلة أدناه الاعتمادية، وتنشئ عميلًا، وتبث قائمة مفردات، وتعالج خطأً.

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.

ما تغلّفه هذه الصفحة