我试图根据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()
}
}发布于 2021-05-31 07:12:36
案例1: Main函数返回一些东西
suspend fun mainFunction(): Boolean = subFunction(getResponse())
fun subFunction(input: Response): Boolean {
// Do something
return something
}
suspend fun getResponse() = withContext(Dispatchers.IO) {
someApiCall()
}这样,我们就可以使用scope.launch了,那么mainFunction的调用者就可以随意使用了。
fun metaMainFunction() {
scope.launch {
val isSomething = mainFunction()
// Do something with isSomething
}
}情况2:mainFunction是即兴的,我们对情况1的metaMainFunction应用相同的行为
fun mainFunction() {
scope.launch {
val response = getResponse()
// Do something with response
}
}最佳实践是被调用者应该决定执行哪个线程。在这种情况下,我们应该始终对getResponse()使用withContext(Dispatchers.IO)。
https://stackoverflow.com/questions/67757013
复制相似问题