简体   繁体   English

如何在不阻塞线程的情况下从挂起 function 返回值

[英]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.

相关问题 Android:在不阻止UI线程的情况下从AsyncTask获取返回值 - Android: Get the return value from an AsyncTask without blocking the UI thread Kotlin 协程为什么以及如何防止线程阻塞,即使没有“暂停”关键字? - Why and how Kotlin coroutine prevents blocking of a thread, even without “suspend” keyword? 如何等待下载线程完成然后返回而又不阻塞UI线程? - How to wait for downloading thread to finish and then return without blocking UI thread? 如何在不阻塞的情况下从单独的线程更新 UI 线程? - How to update UI thread from a separate thread without blocking it? 不适当的阻塞方法调用,但挂起函数“withContext”只能从协程或另一个挂起函数中调用 - Inappropriate blocking method call, but Suspend function 'withContext' should be called only from a coroutine or another suspend function 协程挂起函数和阻塞调用 - Coroutine suspend function and blocking calls 将查询结果返回主线程而不会阻塞 - Return query results to main thread without blocking 如何从Thread返回值? - How to return value from Thread? 如何在不阻塞 UI 线程的情况下用 Room 中的数据填充微调器 - How to fill spinner with data from Room without blocking UI thread 如何从 Fragment 或 Activity 调用挂起功能? - How to call suspend function from Fragment or Activity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM