【发布时间】:2019-07-07 20:04:52
【问题描述】:
总结
Room 会立即插入通过 UI 生成的实体,但会将由 asynctask 发送的实体延迟到生成 asynctask 的(远)端:接收到的实体对象可用并显示在 UI 上,但没有来自数据库的任何 id,妨碍任何其他操作依赖于 id。 插入操作只有在生成的 asynctask 正确停止时才会发生:为什么?以及如何解决这个问题?
更多上下文
生成异步任务
我们使用异步任务来监控套接字并将一些事件(作为 Room 实体)发送回应用程序存储库(如 android 架构组件所期望的那样)。此异步任务基本上在后台连续运行(定期设置一些睡眠),并且仅在应用程序使用结束前停止一段时间(如果操作正确)。到目前为止,它还没有对我们造成任何问题,因为它偏离了最初的短期异步任务概念。 我很清楚我们可以改进设计,但这是另一个主题/问题/时间空洞;-)。
房间插入操作
插入是通过一个专用的异步任务进行的,其中数据库中条目的返回 id 会影响到刚刚插入的实体(参见下面的代码)。这会被记录下来,并且来自 UI 的实体会“立即”持久化,它们会取回自己的 ID,一切都很好。 asynctask 生成的实体,它们等待其“父”任务停止,然后全部插入。
实体构成
最初,实体是在 asynctask 内部生成并通过进度消息发送的。然后对象的构造被移到 asynctask 之外并处于 UI 事件构造的同一级别,但行为相同。 这些事件是一些 long(时间戳)和几个字符串。
从生成asynctask全部从这里开始:
@Override
protected void onProgressUpdate(OnProgressObject... values) {
OnProgressObject onProgressObject = values[0];
if (onProgressObject instanceof OnProgressEvent) {
eventRecipient.sendAutoEvent(((OnProgressEvent) onProgressObject).autoEvent);
}
}
eventRecipient 是 EventsRepository:
public void sendAutoEvent(AutoEvent autoEvent) {
Log.d(LOG_TAG, "got an autoevent to treat...");
EventModel newEvent = EventModel.fromCub(
autoEvent.cubTimeStamp,
autoEvent.description,
autoEvent.eventType
);
addEvent(newEvent);
}
public void addEvent(EventModel event) {
new insertEventAsyncTask(event).execute(event);
// other operations using flawlessly the "event"...
}
private class insertEventAsyncTask extends AsyncTask<EventModel, Void, Long> {
private EventModel eventModel;
public insertEventAsyncTask(EventModel eventModel) {
this.eventModel = eventModel;
}
@Override
protected Long doInBackground(EventModel... eventModels) {
// inserting the event "only"
return eventDao.insert(eventModels[0]);
}
@Override
protected void onPostExecute(Long eventId) {
super.onPostExecute(eventId);
// inserting all the medias associated to this event
// only one media is expected this way though.
eventModel.id = eventId;
Log.d(LOG_TAG, "event inserted in DB, got id : " + eventId);
}
}
【问题讨论】:
-
我已回滚您的编辑。请不要在您的问题标题中添加“已解决”或类似内容。请不要在您的问题中添加解决方案,这就是答案的用途。如果您认为它在接受的答案之外有用,您可以发布自己的答案。
-
好的,感谢您的建议,一旦完全验证,我将添加采用的解决方案:-)。
标签: java android android-asynctask android-room