【发布时间】:2021-08-17 18:32:54
【问题描述】:
我正在尝试根据 repo 调用的响应数据运行一个函数,但遇到了竞争条件/使用协程范围返回数据的问题。基于这两个伪代码块,我想知道是否可以得到一些帮助?
选项 1:如果不使用 runBlocking,则无法在协程范围内返回响应。
fun mainFunction(): Boolean {
return subFunction(getResponse()) //returns boolean
}
private fun getResponse () {
scope.launch{
val response = async { someApiCall }.await()
return response
}
}
选项 2:在调用 subFunction 时,response 的值尚未初始化,从而导致错误。
lateinit var response: MutableList<>
fun mainFunction(): Boolean {
return subFunction(response) //returns boolean
}
private fun getResponse () {
scope.launch{
response = async { someApiCall }.await()
}
}
【问题讨论】:
-
运行挂起方法并返回结果的方法本身应该是
suspend方法。为什么你的getResponse()没有暂停? -
正如@ianhanniballake 提到的,
getResponse应该是suspend fun。你可以使用withContext(Dispatchers.IO)。那么在mainFunction中,可以使用scope.launch,async await不是必须的。 -
你可以使用
withContext从块中返回 -
如果我需要为
mainFunction返回一个值(如布尔值),是否可以在不使其成为挂起函数或withContext的情况下处理getResponse返回?因为如果我们在mainFunction的协程中使用它,它只会返回类型Unit对吧? @TuanChau @ianhanniballake @Anania Jemberu -
是的,我也遇到过这种情况。我让该函数挂起并在我的片段的 runBlocking 块中调用它。
标签: android kotlin android-asynctask kotlin-coroutines coroutine