Android-room持久性库-DAO调用是异步的,因此如何获取回调?

Android-room持久性库-DAO调用是异步的,因此如何获取回调?

问题描述:

从我读到的内容来看 Room不允许您在主线程上发出数据库查询(因为这可能导致主线程延迟).在UI主线程上,一些数据我将如何回叫.让我给你看一个例子.想象一下,我想将我的业务模型数据存储到一个名为事件"的对象中.因此,我们将有一个EventDao对象:

From what i have read Room doesn’t allow you to issue database queries on the main thread (as can cause delays on the main thread)). so imagine i am trying to update a textview on the UI main thread which some data how would i get a call back. Let me show you an example. Imagine i want to store my business model data into a object called Events. We would therefore have a EventDao object:

想象一下,我们在下面有这个DAO对象:

imagine we have this DAO object below:

@Dao
public interface EventDao {

   @Query("SELECT * FROM " + Event.TABLE_NAME + " WHERE " + Event.DATE_FIELD + " > :minDate" limit 1)
   LiveData<List<Event>> getEvent(LocalDateTime minDate);

   @Insert(onConflict = REPLACE)
   void addEvent(Event event);

   @Delete
   void deleteEvent(Event event);

   @Update(onConflict = REPLACE)
   void updateEvent(Event event);

}

现在在某些活动中我有一个textview,我想更新它的值,所以我这样做:

and now in some activity i have a textview and i'd like to update its value so i do this:

 myTextView.setText(EventDao.getEvent(someDate));/*i think this is illegal as im trying to call room dao on mainthread, therefore how is this done correctly ? would i need to show a spinner while it updates ?*/

因为正在从主线程中进行获取,所以我认为我不能这样称呼它并期望平滑更新.什么是最好的方法在这里?

since the fetching is occuring off of the main thread i dont think i can call it like this and expect a smooth update. Whats the best approach here ?

更多信息:我想使用会议室数据库作为检索模型信息的机制,而不是将其静态地保存在内存中.因此,在我通过rest服务下载模型之后,该模型就可以通过db在本地使用.

Some more information: i wanted to use the room database as mechanism for retrieving model information instead of keeping it statically in memory. so the model would be available to me locally through the db after i download it through a rest service.

更新:因此,由于我要返回实时数据,因此我可以这样做:

UPDATE: so since i am returning a livedata then i can do this:

eventDao = eventDatabase.eventDao();
eventDao.getEvent().observe(this, event -> {
     myTextView.setText(event.get(0));
});

,它对很小的东西有用.但是想象一下我的数据库中有一百万个项目.那么当我执行此呼叫时,检索数据将存在延迟.第一次调用此方法时,用户会看到有延迟.如何避免这种情况?要明确一点,有时候我不需要实时数据,我只需要更新一次视图即可.我需要知道该怎么做吗?即使它不与liveData一起使用.

and that works for something very small. but imagine my database has a million items. then when i do this call, there will be a delay retrieving the data. The very first time this gets called it will be visible to the user that there is a delay. How to avoid this ? So to be clear , there are times i do not want live data, i just need to update once the view. I need to know how to do this ? even if its not with liveData.

如果要同步执行查询并且不接收数据集更新通知,只需不要将返回值包装在LiveData对象中即可.查看来自Google的示例代码.

If you want to do your query synchronously and not receive notifications of updates on the dataset, just don't wrap you return value in a LiveData object. Check out the sample code from Google.

看看loadProductSync() 查看更多