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

Written by

on

in

,

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:

db = Room.inMemoryDatabaseBuilder(
    context, MyRoomDatabase::class.java)
    .allowMainThreadQueries()
    .build()

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

About the author:

Catzie Avatar

The homo sapiens behind these blog posts is “Catzie“

Explore my top blog posts:

Comments

Leave a Reply

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