isar / hive

Lightweight and blazing fast key-value database written in pure Dart.
Apache License 2.0
4.07k stars 404 forks source link

Typed box, persisting a value on the object? #437

Open mistyn8 opened 4 years ago

mistyn8 commented 4 years ago

Question Is this following the recommended way to persist a single value in a typed box??

Code sample

var hiveBoxUserData = await Hive.openBox<UserData>('userData');
hiveBoxUserData.values.first.stats.all.impact += mission.impact;
await hiveBoxUserData.putAt(0, hiveBoxUserData.values.first);

ps hiveBoxUserData.values.first.stats.all.impact += mission.impact; seems to persist the value in memory, but on app reload it's lost.

Version [√] Flutter (Channel dev, 1.22.0-12.0.pre, on Microsoft Windows [Version 10.0.19041.450], locale en-GB)

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.2) ! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses [√] Android Studio (version 4.0) [√] VS Code (version 1.49.0) [√] Connected device (1 available)

themisir commented 4 years ago

I'm using something like this:

var user = Hive.box('user_info').get(0);
user.prop = newValue;
Hive.box('user_info').put(0, user);

You have to call Box.put to update persisted data.

mistyn8 commented 4 years ago

@TheMisir thanks,

just to extend on this,

If I was to filter ... return hiveBoxFlags.values.where((f) => f.missionUid == missionUid).first() how do I get a reference to the index or key.. to be able to update and put?

themisir commented 4 years ago

You can use HiveObject.key property to get object's key. (You have to extend objects stored in box with HiveObject type).

PS: HiveObject also has .save method which will put itself into the box with matching key. (Same thing as manually putting to the box).

mistyn8 commented 4 years ago

you beat me to it.. ;-) could I suggest adding a link for typed objects and persistence in the typeAdapter doc, and filters? ;-)

.. hadn't seen https://docs.hivedb.dev/#/custom-objects/hive_object

where in the type adapter you can class Custom extend HiveObject to gain save(), key etc..

var hiveBoxUserData = await Hive.openBox<UserData>('userData');
hiveBoxUserData.values.first.stats.all.impact += mission.impact;
await hiveBoxUserData.values.first.stats.all.save();
@HiveType(typeId: 12)
@JsonSerializable()
class Stat extends HiveObject {
  @HiveField(0)
  double impact;
...