尝试尝试mvvm和livedata,我在数据库Room中有一个查询
@Query("SELECT * FROM User ")
fun getAllUsers(): LiveData<MutableList<User>>
@Query("SELECT * FROM User ")
fun getAllUsersRx(): Flowable<MutableList<User>>
我从 ViewModel 调用方法,两种情况下都会发生,但如果所有事情都通过 rx 在另一个线程中工作,那么在 LiveData 的情况下,所有事情都应该在 mainThread 中发生。但是为什么 Room 没有给出错误 IllegalStateException: Cannot access the database on the main thread 呢?那么这种情况下使用LiveData直接向Room请求数据是否正确,还是需要自己将操作转移到另一个线程?
最佳答案
then in the case of LiveData everything should happen in mainThread.
您在主线程上观察它并在主线程上接收查询项,但查询本身是在 ArchTasksExecutors.ioThread()
执行器(后台线程)上执行的。
But then why doesn’t Room give the error IllegalStateException: Cannot access the database on the main thread?
因为查询是在后台线程上执行的,然后在获取任务完成时通过 liveData.postValue(queriedData)
传递给 UI 线程。
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 自动处理“在后台线程上查询,并将结果传递给 UI 线程”。您可以在生成的代码中检查这是如何发生的,但从技术上讲,Room 已经为您做到了这一点。
您不需要 Rx 来让 Room 在后台线程上运行查询,仅 LiveData 就足够了。
关于android - 请求ROOM时可以直接使用LiveData吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55184585/