Search code examples
androidkotlinmvvmrepositorykotlin-coroutines

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..?


Solution

  • 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)
    }