Search code examples
androiddatabaserx-javaandroid-roomandroid-livedata

Is it possible to use LiveData directly when requesting ROOM?


Trying to try mvvm and livedata, I have a query in the database Room

@Query("SELECT * FROM User ")
fun getAllUsers(): LiveData<MutableList<User>>

@Query("SELECT * FROM User ")
fun getAllUsersRx(): Flowable<MutableList<User>> 

I call the methods from the ViewModel and everything comes in both cases, but if everything works in another thread via rx, then in the case of LiveData everything should happen in mainThread. But then why doesn’t Room give the error IllegalStateException: Cannot access the database on the main thread? And is it correct in this case to directly request data from Room using LiveData, or do I need to transfer the operation to another thread by myself?


Solution

  • then in the case of LiveData everything should happen in mainThread.

    You observe it on the main thread and receive the queried items on the main thread, but the query itself is executed on the ArchTasksExecutors.ioThread() executor (background thread).

    But then why doesn’t Room give the error IllegalStateException: Cannot access the database on the main thread?

    Because the query is being executed on a background thread, then passed to UI thread via liveData.postValue(queriedData) when the fetch task is compelte.

    And is it correct in this case to directly request data from Room using LiveData, or do I need to transfer the operation to another thread by myself?

    LiveData handles "querying on background thread, and passing the results to you to the UI thread" automatically. You can check in the generated code how this happens, but technically Room does this for you already.


    You don't need Rx to make Room run its queries on background thread, LiveData alone is sufficient.