ObjectBox 框作为队列

问题描述

是否可以限制一个盒子最多包含 N 个对象?

我想要实现的是类似于一个带有 ObjectBox 的队列。

假设我想要一个最多包含 3 个对象的队列,并且我已经有 id 为 1、2 和 3 的对象。

当我在里面放入一个新对象时,这个对象的 id 为 4,现在盒子将包含 1、2、3 和 4。

但我想要的是只包含 2、3 和 4 的盒子。

这是否可以使用当前的 ObjectBox 功能以及可用的 dart 库 API?

如果没有,您对如何使用 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;
  });
}

解决方法

如果您想避免“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;
  });
}