android - 在 kotlin 协程中实现 async-await()

标签 android kotlin kotlin-coroutines coroutine

我创建了如下函数:

fun getPercentage(id:String): String {
    var percentage=""
    scope.launch {
        percentage=repo.getPercentage(id)?.get(0)?.percent.toString()
        Log.e("$$$ value >>","$$$ value >>"+percentage)
    }
    Log.e("$$$ value outside >>","$$$ value >>"+percentage)
    return percenatge
}

在这里,我无法使用变量返回更新后的值:百分比。

我得到的日志如下:

$$$ value outside >> 
$$$ value >> 50

表示我无法返回最新值。流程出了点问题。

有人建议我使用 async{} 和 await()。但我不知道它在这里会有什么帮助?

请指导。谢谢。

最佳答案

launch函数在后台启动协程,然后继续。因此,您的“外部”代码在“内部”协程完成之前运行。

使用 async函数而不是返回一个 Deferred来自协程的值:

fun getPercentage(id:String): Deferred<String> {
    return scope.async {
        percentage=repo.getPercentage(id)?.get(0)?.percent.toString()
        Log.e("$$$ value >>","$$$ value >>"+percentage)
    }
}

当然要注意,更有可能的是你想让getPercentage成为一个挂起函数,然后直接调用await:

suspend fun getPercentage(id:String): String {
    val percentageDeferred = scope.async {
        percentage=repo.getPercentage(id)?.get(0)?.percent.toString()
        Log.e("$$$ value >>","$$$ value >>"+percentage)
    }
    val percentage = percentageDeferred.await()
    Log.e("$$$ value outside >>","$$$ value >>"+percentage)
    return percentage    
}

您也可能想在 await 之前执行其他操作,否则您最好将 repo.getPercentage 也设为暂停函数,然后调用它直接:

suspend fun getPercentage(id:String): String {
    // if repo.getPercentage is a suspend function, this call suspends
    // like the await in the previous example
    val percentage = repo.getPercentage(id)?.get(0)?.percent.toString()
    Log.e("$$$ value outside >>","$$$ value >>"+percentage)
    return percentage    
}

参见 Concurrent using async在 Kotlin 文档中。

关于android - 在 kotlin 协程中实现 async-await(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66987698/

相关文章:

java - Google map Activity 在 "getLastKnownLocation"中崩溃

android - Kotlin 如何创建目录。 MkDir() 不工作

Android 4.x Kotlin方法引起的VerifyError

android - 为什么我需要权限 "android.permission.WRITE_OWNER_DATA"

java - 如何将 AIResponse gson 转换为可在 Text to Speech 上使用的文本?

android - 创建类似 HTC Sense 的 Android 用户界面

kotlin - 如何使用Exposed和Kotlin在db中设置当前日期

kotlin - 如何在Kotlin中将通用作用域的Lambda传递给类方法?

尽管调用了 launch 方法,Kotlin 协程仍同步运行

kotlin - 为什么我在 Kotlin 中使用了 runBlocking 后还需要添加 job.join()?