Lingara Lingara दस्तावेज़ मार्गदर्शिकाएँ API लाइब्रेरी ऐप बनाएं वेब ऐप
भाषा: हिन्दी

Kotlin

यह पेज अंग्रेज़ी से अनुवादित है। अगर दोनों में अंतर हो, तो अंग्रेज़ी पेज सही है। अंग्रेज़ी पेज पढ़ें

Kotlin लाइब्रेरी Maven Central पर com.getlingara:lingara-kotlin है। यह JVM पर चलती है, इसके लिए Java 17 और Kotlin 2.2 या उसके बाद का संस्करण चाहिए, और यह kotlinx.coroutines और kotlinx.serialization का उपयोग करती है।

इसे कैसे इस्तेमाल करें

  • हर कॉल एक suspend फ़ंक्शन है। कॉल रद्द करने के लिए coroutine रद्द करें, या डेडलाइन के लिए withTimeout का उपयोग करें; आपको अपना ही CancellationException दिखता है, कभी लपेटा हुआ नहीं।
  • स्ट्रीम एक EventStream है, एक Flow जिसे आप एक बार collect करते हैं। इसे use के भीतर collect करें, ताकि काम पूरा होने पर यह बंद हो जाए। इवेंट एक sealed interface के अंतर्गत data classes हैं, जिन्हें when से मिलाया जाता है।
  • एरर sealed class LingaraException को एक्सटेंड करते हैं, इसलिए उन पर when संपूर्ण होता है। retryAfter एक Duration है, या null जब API ने कोई इंतज़ार नहीं बताया।
  • 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.

यह पेज क्या रैप करता है