简体   繁体   中英

Calling asyn method in synchronous way in Kotlin coroutine

I am trying to run a Google ML Kit function and the result will be in callback and need to pass that value as a return type for the method in which it was executing in Kotlin. I tried some of the samples of Kotlin coroutines but still I am missing something and it was failing. I am still learning Kotlin.

internal fun processImageSync(image: InputImage) : String{
        var doctype = ""
        val recognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
        recognizer.process(image)
            .addOnSuccessListener { visionText ->
                var texttoscan = visionText.text.trim()
                doctype = findstr(texttoscan)    
            }
            .addOnFailureListener { 
            }
    return doctype;
    }

How can I solve the issue?

Use kotlinx-coroutines-play-services module

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.0")
}

Use extension Task.await

internal suspend fun processImageSync(image: InputImage): String {
    val recognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
        
    return recognizer.process(image)
        .await()
        .let { visionText -> findstr(visionText.text.trim()) }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM