Android viewModelScope中的If语句
为什么函数返回总是错误的?如何解决这个问题Android viewModelScope中的If语句,android,kotlin-coroutines,Android,Kotlin Coroutines,为什么函数返回总是错误的?如何解决这个问题 fun testFun(id: Int): Boolean { var isExists = false viewModelScope.launch { val itemFromDb = database.getDetails(id) if (itemFromDb != null) // never executing isExists = true } retur
fun testFun(id: Int): Boolean {
var isExists = false
viewModelScope.launch {
val itemFromDb = database.getDetails(id)
if (itemFromDb != null) // never executing
isExists = true
}
return isExists // always return false
}
正如@Abdul所说,您的协同程序切换到另一个线程并继续执行。但是,
testFun
方法不会停止工作,并在协同程序完成之前完成
你可以重写你的代码。例如,使testFun
成为一个挂起的函数,并将其中的所有内容写入一个块中。或者同步方法和协同程序。我通常使用withContext(Dispatchers.IO)
,也不使用viewModelScope.launch
可能是错误的解决方案:
fun suspend something(): Boolean {
var result = false
result = withContext(Dispatchers.IO) {
...
true
}
... // Other code in the main thread.
return result
}
fun something(): Boolean {
var result = false
val job = launch() {
result = withContext(Dispatchers.IO) {
...
true
}
... // Other code in the main thread.
}
return result
}
正如@Abdul所说,您的协同程序切换到另一个线程并继续执行。但是,
testFun
方法不会停止工作,并在协同程序完成之前完成
你可以重写你的代码。例如,使testFun
成为一个挂起的函数,并将其中的所有内容写入一个块中。或者同步方法和协同程序。我通常使用withContext(Dispatchers.IO)
,也不使用viewModelScope.launch
可能是错误的解决方案:
fun suspend something(): Boolean {
var result = false
result = withContext(Dispatchers.IO) {
...
true
}
... // Other code in the main thread.
return result
}
fun something(): Boolean {
var result = false
val job = launch() {
result = withContext(Dispatchers.IO) {
...
true
}
... // Other code in the main thread.
}
return result
}
所以这也是一个可能的解决方案。我在这里试过,效果很好
fun something(): Boolean = runBlocking (Dispatchers.IO){
return@runBlocking database.getDetails(id)!=null
}
所以这也是一个可能的解决方案。我在这里试过,效果很好
fun something(): Boolean = runBlocking (Dispatchers.IO){
return@runBlocking database.getDetails(id)!=null
}
这个解决方案适合我
suspend fun testFun(id: Int): Boolean {
var isExists = false
val result = viewModelScope.await {
val itemFromDb = database.getDetails(id)
if (itemFromDb != null)
isExists = true
return@async isExists
}
result.await()
return isExists
}
这个解决方案适合我
suspend fun testFun(id: Int): Boolean {
var isExists = false
val result = viewModelScope.await {
val itemFromDb = database.getDetails(id)
if (itemFromDb != null)
isExists = true
return@async isExists
}
result.await()
return isExists
}
当您启动一个协同程序时,它会转移到另一个线程,返回的是当前线程,它不会等待results@Abdul,您应该将其作为答案(并更改代码)。如果(itemFromDb!=null)从未调用过,您确定
吗?@CoolMind,是的,我确定。和数据库。getDetails(id)也是挂起的功能(房间)。可能出现了任何错误?我经常使用try-catch。当你启动一个协同程序时,它会转移到另一个线程,返回的是当前线程,它不会等待results@Abdul,您应该将其作为答案(并更改代码)。如果(itemFromDb!=null)
从未调用过,您确定吗?@CoolMind,是的,我确定。和数据库。getDetails(id)也是挂起的功能(房间)。可能出现了任何错误?我经常用try-catch。