withContext(Dispatchers.IO) how to use for room

Viewed 3535

In our app there are so many queries and now we are using ROOM , I want to confirm that what is proper way to use Coroutine before we was using like this

In Dao

  @Query("SELECT * FROM VISITS")
    suspend fun getAllVisits(): List<Visits>

And we are getting like this

fun getAll(visit: Visits?) = runBlocking {
        Log.i(TAG, "addOrUpdateRecord")
        try {

val list = ArrayList<Visits>()
                list.addAll(async {
                    visitsDao.getAllVisits()
                }.await())

}

But in some articale i have read that runblocking is for only testing not production please guide me proper way Thank you

3 Answers

If you need a coroutine scope to launch a coroutine you have either lifecycleScope or viewModelScope ready to use according to your needs.

Inside an Activity:

fun myMethod() {
    lifecycleScope.launch {
        val list = visitsDao.getAllVisits()
        //Do something with list here
            ...
    }
}

Inside a Fragment:

fun myMethod() {
    viewLifecycleOwner.lifecycleScope.launch {
        val list = visitsDao.getAllVisits()
        //Do something with list here
            ...
    }
}

Inside a ViewModel:

fun myMethod() {
    viewModelScope.launch {
        val list = visitsDao.getAllVisits()
        //Do something with list here
        ...
    }
}

Inside a regular class:

class MyPresenter: CoroutineScope {
    private val myJob = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Default + myJob
    
    ...

    fun myMethod() {
        launch {
            val list = visitsDao.getAllVisits()
            //Do something with list here
            ...
        }
    }
    
    ...

    //Call clear when required
    fun clear() {
        this.myJob.cancel()
    }
}

You can use something like this

GlobalScope.launch { 
            withContext(Dispatchers.IO){
                // your query
            }
        }

In Viewmodel :

viewmodelScope.launch(Dispatchers.IO){
  visitsDao.getAllVisits()
}

OR another suspend function

suspend fun addAll() {
    visitsDao.getAllVisits().run{
     ArrayList<Visits>().addAll(this)

   }
}

EvenMore, just use flow, and you can do with livedata builder/map/asLiveData etc.

Related