简体   繁体   English

我们可以在生产环境中使用 runblocking 和协程来进行房间查询吗?

[英]can we use runblocking with coroutine for room queries in production?

In our product we are using MVP pattern and in Room examples and after long searching I am getting all example with MVVM but now I found this way to run my Room queries using runblocking everything working smoothly I want to know that is this good way to use coroutines, I have heard that runblocking is not recommended for production在我们的产品中,我们使用 MVP 模式和 Room 示例,经过长时间的搜索,我得到了所有使用 MVVM 的示例,但现在我发现这种方式可以使用 runblocking 运行我的 Room 查询,一切运行顺利我想知道这是使用的好方法协程,听说生产环境不推荐runblocking

@Query("""SELECT V.* FROM VISITS AS V LEFT JOIN ORDERS AS O ON O.visitId = V.visitId 
        WHERE V.visitComplete = 1 AND V.visitId = :visitId AND (V.shopClosed = 1 OR O.orderTotal > 0)""")
suspend fun getCompletedVisitByVisitId(visitId: Int): Visits

And in my table Helper I am getting result like this在我的表助手中,我得到了这样的结果

fun getCompletedVisitByVisitId(visitId: Int): Visits? = runBlocking {

    var data: Visits? = null
    try {
        data = async {
            visitsDao.getCompletedVisitByVisitId(visitId)
        }.await()
    } catch (e: SQLException) {
        CustomMethods.errorLog(e, "getCompletedVisitByVisitId", ErrorLog.TYPE_ERROR, ErrorLog.APPLICATION_ERROR, context)
        e.printStackTrace()
    }
    data
}

override fun getCompletedVisitByVisitId(visitId: Int): Visits? {
        return visitsTableHelper!!.getCompletedVisitByVisitId(visitId)
    }

androidx.lifecycle package provides extension function for lifecycle owners (activity,fragment,viewmodel etc). androidx.lifecycle package 为生命周期所有者(活动、片段、视图模型等)提供扩展 function。 So, it would be convenient to to use the lifecycleScope.launch for MVP pattern.因此,将lifecycleScope.launch范围.launch 用于 MVP 模式会很方便。 By this way your coroutine jobs will automatically get canceled when the lifecycle owner is not in its active state.通过这种方式,当生命周期所有者不在其活动 state 中时,您的协程作业将自动取消。

So, you code can be life below:所以,你的代码可以是下面的生活:

override fun onCreate(savedInstanceState: Bundle?) {
    ...
    .....
    lifecycleScope.launch {
       try {
          val visits = getCompletedVisitByVisitId(someNumber)
          // do something with your data
       } catch (e: Exception) {
          //handle exception 
       }
    }
}
suspend fun getCompletedVisitByVisitId(visitId: Int): Visits? {

    var data: Visits? = null
    try {
        data = visitsDao.getCompletedVisitByVisitId(visitId)
    } catch (e: SQLException) {
        CustomMethods.errorLog(e, "getCompletedVisitByVisitId", ErrorLog.TYPE_ERROR, ErrorLog.APPLICATION_ERROR, context)
        e.printStackTrace()
    }
    data
}

Also import the dependencies:同时导入依赖项:

def lifecycle_version = "2.3.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM