[英]Android: Get the return value from an AsyncTask without blocking the UI thread
[英]How to return value from suspend function without blocking thread
我有一個掛起方法:checkIfAvailable(),它返回一個 Boolean。 我想獲得那個 boolean 值,然后在我的活動中使用它。 我嘗試以下方式(不確定是否應該這樣做):
suspend fun checkIfAvailable(year: Int): Boolean = viewModelScope.async{
return@async dao.checkIfAvailable(year)
}.await()
這將返回 boolean。 問題是我不能使用 boolean,因為 function 必須是暫停 function 必須在其中調用。
如何在不阻塞主線程的情況下獲得 boolean 值?
我在我的活動中使用 runBlocking 進行了嘗試:
fun something(tag: Int): Boolean {
return runBlocking {
return@runBlocking checkIfAvailable(tag)
}
}
但這會崩潰或阻塞主線程。
我只需要一種方法來將值從掛起 function 中取出並放入變量中而不會阻塞線程。
在您的活動中使用它:
lifecycleScope.launch(Dispatchers.Default) {
val result = checkIfAvailable(year)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.