Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coroutine Scope inside repository class

Lets assume that i have a list of Dtos, i want to loop throught them and set some values and then insert/update them to my Room database. So from my ViewModel i call the repository class, run the loop inside there and then i call dao.insertItems(list).


fun updateItems(itemList: List<ItemDto>) {
        val readDate = DateUtils.getCurrentDateUTCtoString()
        ???SCOPE???.launch(Dispatchers.IO) {
            for (item in itemList)
                item.readDate = readDate
            itemDao.updateItems(itemList)
        }
    }

The question is what kind of courtineScope do i have to use inside the Repository class. Do i have to create a repositoryScope with Dispatchers.Main..? Perhaps a GlobalScope..?

like image 740
james04 Avatar asked Nov 26 '19 23:11

james04


2 Answers

You should write your repository APIs as suspend functions instead, like so

suspend fun updateItems(itemList: List<ItemDto>) = withContext(Dispatchers.IO) {
    val readDate = DateUtils.getCurrentDateUTCtoString()
    for (item in itemList)
        item.readDate = readDate
    itemDao.updateItems(itemList)
}

Edit: if you need this to run even after the viewmodel is destroyed, launch it with NonCancellable,

suspend fun updateItems(itemList: List<ItemDto>) = withContext(Dispatchers.IO + NonCancellable) {
    val readDate = DateUtils.getCurrentDateUTCtoString()
    for (item in itemList)
        item.readDate = readDate
    itemDao.updateItems(itemList)
}
like image 160
Francesc Avatar answered Sep 18 '22 11:09

Francesc


Create your method inside repository as suspend fun and use withContext(Dispatchers.IO)

e.g.

suspend fun updateItems() = withContext(Dispatchers.IO) {
    //you work...
}
like image 20
Amir Raza Avatar answered Sep 18 '22 11:09

Amir Raza