[英]How to return value from suspend function without blocking thread
I have a suspend method: checkIfAvailable() that returns a Boolean.我有一个挂起方法:checkIfAvailable(),它返回一个 Boolean。 I want to get that boolean value and then use it in my activity.我想获得那个 boolean 值,然后在我的活动中使用它。 I try this the following way(not sure if this is how it should be done):我尝试以下方式(不确定是否应该这样做):
suspend fun checkIfAvailable(year: Int): Boolean = viewModelScope.async{
return@async dao.checkIfAvailable(year)
}.await()
This returns a boolean.这将返回 boolean。 The problem is that i can't use that boolean, because the function must be a suspend function as await() must be called inside one.问题是我不能使用 boolean,因为 function 必须是暂停 function 必须在其中调用。
How do i get the boolean value without blocking the main thread ?如何在不阻塞主线程的情况下获得 boolean 值?
I tried it with runBlocking in my activity:我在我的活动中使用 runBlocking 进行了尝试:
fun something(tag: Int): Boolean {
return runBlocking {
return@runBlocking checkIfAvailable(tag)
}
}
but this crashes or blocks the mainthread.但这会崩溃或阻塞主线程。
I just need a way to get the value out of the suspend function and into a variable without blocking the thread.我只需要一种方法来将值从挂起 function 中取出并放入变量中而不会阻塞线程。
Use this inside your activity:在您的活动中使用它:
lifecycleScope.launch(Dispatchers.Default) {
val result = checkIfAvailable(year)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.