0

When I update an item it says Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
The app uses Jetpack compose. I have a function in my DAO used to update an item

@Update
fun update(item:Item)

And a repository to access the database

fun update(item:Item){
    itemDao.update(item)
}

In my viewmodel, I use viewModelScope to call the function

fun update(item: Item){
        viewModelScope.launch {
            itemRepository.update(item)
        }
    }

However, when I call itemViewModel.update(item) in an onclick() scope, the error still occurs which I dont know why.

KevinT3Hu
  • 13
  • 4
  • 1
    Try this: https://stackoverflow.com/questions/57657741/cannot-access-database-on-the-main-thread-since-it-may-potentially-lock-the-ui?noredirect=1&lq=1 – Álysson Alexandre Feb 10 '22 at 01:37
  • 1
    shouldn't your `update()` function in your DAO be a suspend function? I mean, even if called from a coroutine scope, `viewModelScope` is tied to the main thread. Maybe explicitly declaring `update()` as a suspend function could help. – Arthur Bertemes Feb 10 '22 at 01:41
  • Yes. The top answer on the linked question is outdated in the sense that it doesn’t mention this preferable solution of marking the function suspend. – Tenfour04 Feb 10 '22 at 05:49
  • Making it suspend indeed worked. Anyway, maybe it was a bug in the Android Studio that when I wrote it as suspend, it said that the qualifier was redundant which was why I then removed it. – KevinT3Hu Feb 10 '22 at 05:57

0 Answers0