我每隔x小时运行一次JobService来清理重复项(在5秒内创建的对象)。
首先,我加载每个MyContainer
(对触发插入排序或不起作用),然后加载具有匹配字段和时间戳在5secs内的每个对象。找到的对象已删除
//Simplified for this question
public static void doCleanUp(Context context) {
Realm realm = context.mRealm;
realm.executeTransaction(realm1 -> {
RealmResults<MyContainer> allContainer = realm1.where(MyContainer.class)
.findAllSorted("timestamp", Sort.ASCENDING);
// implicit snapshot
for (MyContainer item : allContainer) {
if (item.isValid()) {
RealmResults<MyContainer> toDelete = realm1.where(MyContainer.class)
.notEqualTo("rowId", item.getRowId())
.equalTo("name", item.getName())
.equalTo("path", item.getPath())
.lessThan("timestamp", item.getTimestamp() + 5000)
.findAll();
if (toDelete.size() > 0) {
Log.i(TAG, "RealmCleanupJobService: deleteing objects " + toDelete.size());
toDelete.deleteAllFromRealm();
}
}
}
});
}
在另一个服务中,changeListener正在侦听,但它只对插入做出反应:
private void setupRealmCollectionListener() {
mThreadPool = Executors.newCachedThreadPool();
mAllContainer = getRealm().where(MyContainer.class).findAllSorted("timestamp", Sort.DESCENDING);
mAllContainer.addChangeListener((myContainers, changeSet) -> {
if (changeSet == null) return;
OrderedCollectionChangeSet.Range[] insertions = changeSet.getInsertionRanges();
for (OrderedCollectionChangeSet.Range range : insertions) {
for (int i = 0; i < range.length; i++) {
MyContainer ac = getRealm().copyFromRealm(myContainers.get(range.startIndex + i));
mThreadPool.execute(() -> {
// ...
});
}
}
});
}
删除按预期工作。但是,会出现一些插入内容:
我如何解决这个问题?为什么会出现插入?我想过一些解决方法,比如删除和读取监听器。