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

A Filipino programmer with a variety of interests such as baking, singing, making up silly song/rap lyrics, K-pop, drawing, creating unique dessert flavors, obsessing about finding out how some things works, board games, anime, video games, and forgetting things that usually go in her long list of interests. Running small-time online dessert shops Cookies PH and Catzie's Cakery.

Leave a Reply

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