android - 请求ROOM时可以直接使用LiveData吗?

标签 android database rx-java android-room android-livedata

尝试尝试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/

相关文章:

android - 在具有 2 个不同模式的 Greendao 中使用超过 1 个数据库 - Android

android - OpenGL ES 模板操作

MySQL 在引用表中使用 like 表达式

java - 在 Rxjava 中创建线程

java - 检测 SD 卡是否存在始终返回 true

java - Android应用程序写入文件,找不到结果

python - 将 TXT 加载到 postgres 数据库中,将不存在的列填充为 null

c# - 从连接字符串中删除了数据库

android - 如何等到一堆电话结束再打一个电话

android - Retrofit + RxJava 链接多个请求并聚合结果