1
votes

Is it possible to limit a box to contain a maximum of N objects inside?

What I want to achieve is to have something similar to a queue with ObjectBox.

Let's say I want a queue with a max of 3 objects, and I already have objects with ids 1, 2, and 3 inside.

When I put a new object inside, this object will have id 4 and now the box will contain 1, 2, 3, and 4.

But what I want is the box to contain only 2, 3, and 4.

Is this possible with the current ObjectBox features and also with the available dart library API?

If not, do you have any suggestions on how to implement this in the most optimized way with ObjectBox?

Update:

Here is the solution I have now after finding out ObjectBox has support for transactions:

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;
  });
}
1

1 Answers

0
votes

If you want to avoid "ID arithmetic", which might be a bit fragile in the long run, you can also get all object IDs via a query. Then, delete the first one(s) if there are too many objects in the DB. This is more robust and flexible, e.g. Person is inserted somewhere else, and/or multiple Person objects must be deleted.

Based on your code, I made the following adjustments to illustrate the approach (did not check with the compiler):

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;
  });
}