Skip to content Skip to sidebar Skip to footer

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 runbl

Solution 1:

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:

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

    vardata: Visits? = nulltry {
        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"

Post a Comment for "Can We Use Runblocking With Coroutine For Room Queries In Production?"