简体   繁体   English

从后台线程查询房间数据库

[英]Room Database Query from background Thread

I have read that one of the ways to query data in room database is to use Livedata which can be used on the main thread as it is asynchronous. 我已经读过,在房间数据库中查询数据的方法之一是使用Livedata,它可以在主线程上使用,因为它是异步的。

I would like to use LiveData instead of RxJava or AsyncTask. 我想使用LiveData而不是RxJava或AsyncTask。

For this in my repository class I have function getSomeData() which returns LiveData> and I call this function in my viewModel constructor: 对于我的存储库类,我有函数getSomeData()返回LiveData>我在viewModel构造函数中调用此函数:

private var mObservableSomeData: LiveData<List<SomeData>>

init {
    mObservableSomeData = repository.getSomeData()
}

fun getSomeData(): LiveData<List<SomeData>> {
    return mObservableSomeData
}

However it crashes saying: 然而它崩溃说:

Cannot access database on the main thread since it may potentially lock the UI for a long period of time. 无法访问主线程上的数据库,因为它可能会长时间锁定UI。

What should I do? 我该怎么办?

As pointed out by @LieForBananas, most probably you are getting error while doing insertion. 正如@LieForBananas所指出的,很可能你在插入时会出错。 Whenever you have @Query and you are wrapping returned data into an observable eg LiveData or Flowable, your query gets executed on background thread by default. 每当你有@Query并且将返回的数据包装到一个可观察的例如LiveData或Flowable时,默认情况下你的查询将在后台线程上执行。

Remember that Room Database ensure that the query returning observable is run on background thread. 请记住,Room Database确保返回observable的查询在后台线程上运行。 This is why, if you are wrapping returned value in Flowable, you don't have to explicitly write .subscribeOn(Schedulers.io) while creating observer. 这就是为什么,如果要在Flowable中包装返回值,则不必在创建观察者时显式写入.subscribeOn(Schedulers.io) Whereas If you are using Flowable for network call(Single might be better because usually we need to emit only once), then you have to explicitly write .subscribeOn(Scheduler.io()) to run the call on a background thread. 如果你使用Flowable进行网络调用(Single可能更好,因为通常我们只需要发出一次),那么你必须显式写.subscribeOn(Scheduler.io())来在后台线程上运行调用。

Room doesn't allow database operation on the Main thread unless you allow database on the main thread with allowMainThreadQueries() . 除非您允许主线程上的数据库使用allowMainThreadQueries()否则Room不允许在主线程上进行数据库操作。

MyApp.database = Room.databaseBuilder(this,AppDatabase::class.java,"MyDatabase")
                     .allowMainThreadQueries()
                     .build()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM