Reputation: 61
Why function return always false? And how to fix this?
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
}
Upvotes: 2
Views: 301
Reputation: 61
This solution suits me.
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
}
Upvotes: 0
Reputation: 887
So this is also a possible solution. I have tried it here and working fine
fun something(): Boolean = runBlocking (Dispatchers.IO){
return@runBlocking database.getDetails(id)!=null
}
Upvotes: 1
Reputation: 28875
As @Abdul said, your coroutine switches to another thread and continues there. But a testFun
method doesn't stop working and finishes before the coroutine finish.
You can rewrite your code. For instance, make testFun
a suspended function and write everything inside in one block. Or synchronize the method and the coroutine. I usually do this with withContext(Dispatchers.IO)
, didn't work with viewModelScope.launch
either.
Maybe wrong solutions:
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
}
Upvotes: 2