是否可以将一个盒子限制为最多包含N个对象?
我想要实现的是使用ObjectBox实现类似于队列的东西。
假设我想要一个最多包含3个对象的队列,并且我已经有了I为1、2和3的对象。
当我将一个新对象放入其中时,该对象的id将为4,现在框中将包含1、2、3和4。
但我想要的是这个盒子只包含2、3和4。
对于当前的ObjectBox特性和可用的dart库应用编程接口,这是否可能?
如果没有,您对如何使用ObjectBox以最优化的方式实现这一点有什么建议吗?
更新:
这是我现在发现ObjectBox支持事务后的解决方案:
int maxValue = 50;
int addNewRow(Person person, Store store, Box<Person> box) {
return store.runInTransaction(TxMode.write, () {
final id = box.put(person);
final toBeRemovedId = id - maxValue + 1;
if (toBeRemovedId > 0) {
if (!box.remove(toBeRemovedId)) {
throw "hue";
}
}
return id;
});
}发布于 2021-05-05 22:51:48
如果你想避免"ID算法“,这在长期运行中可能有点脆弱,你也可以通过一个查询获得所有的对象ID。然后,如果数据库中的对象太多,请删除第一个。这更加健壮和灵活,例如,Person被插入到其他地方,和/或必须删除多个Person对象。
根据您的代码,我做了以下调整来说明该方法(没有检查编译器):
int maxValue = 50;
int addNewRow(Person person, Store store, Box<Person> box) {
return store.runInTransaction(TxMode.write, () {
final id = box.put(person);
final ids = box.query().build().findIds()
if (ids.length > maxValue) {
final toRemove = maxValue - ids.length
for (var index = 0; i < toRemove; i++) {
box.remove(ids[index])
}
}
return id;
});
}https://stackoverflow.com/questions/67402191
复制相似问题