Fix coroutine error: Cannot access database on the main thread // Android Dev Diary

As I was running a test for a ViewModel function, I encountered the following error:

[...] Main Thread @coroutine java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

I think it may be caused by the viewModelScope from viewModelScope.launch {} being used by the running test, which may not be accessible during unit tests.

What I did to fix this error on my unit test was to enable main thread operations in my in-memory Room database test instance. I simply added .allowMainThreadQueries() while building the database instance like so:

Is that the best way to do it? If you got a better suggestion, please comment! I’d love to hear about it.

Related Posts:

Posts that may be related to "Fix coroutine error: Cannot access database on the main thread // Android Dev Diary":

Catzie

An odd human being who happens to have a variety of ever-changing interests, but right now they are programming, making up silly song/rap lyrics, K-pop, drawing, creating unique dessert/drink flavors, obsessing about finding out how some things works, automation, anime, video games... Ran online dessert shops Cookies PH and Catzie's Cakery in her past life.

Leave a Reply

Your email address will not be published. Required fields are marked *