[英]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.我正在尝试运行 Google ML Kit function,结果将在回调中,并且需要将该值作为返回类型传递给它在 Kotlin 中执行的方法。 I tried some of the samples of Kotlin coroutines but still I am missing something and it was failing.
我尝试了 Kotlin 协程的一些样本,但我仍然遗漏了一些东西并且它失败了。 I am still learning Kotlin.
我还在学习 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使用kotlinx-coroutines-play-services 模块
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.6.0")
}
Use extension Task.await使用扩展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()) }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.