简体   繁体   中英

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

@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). So, it would be convenient to to use the lifecycleScope.launch for MVP pattern. By this way your coroutine jobs will automatically get canceled when the lifecycle owner is not in its active 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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