请求ROOM时是否可以直接使用LiveData?
Is it possible to use LiveData directly when requesting ROOM?
正在尝试mvvm和livedata,我在数据库房间有查询
@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 自动处理 "querying on background thread, and passing the results to you to the UI thread"。您可以检查生成的代码是如何发生的,但从技术上讲,Room 已经为您完成了。
您不需要 Rx 来使 Room 运行 在后台线程上进行查询,仅 LiveData 就足够了。
正在尝试mvvm和livedata,我在数据库房间有查询
@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 自动处理 "querying on background thread, and passing the results to you to the UI thread"。您可以检查生成的代码是如何发生的,但从技术上讲,Room 已经为您完成了。
您不需要 Rx 来使 Room 运行 在后台线程上进行查询,仅 LiveData 就足够了。