hive icon indicating copy to clipboard operation
hive copied to clipboard

Avoid duplicating objects.

Open Turskyi opened this issue 4 years ago • 1 comments

Question How to avoid duplicating objects in datastore? What is the best practice let Hive know that the object must be overridden or ignored instead of duplicating.

Code sample Future addCountries(List<CountryDataEntity> countries) async { final Box<CountryDataEntity> box = await openDataBox(); box.addAll(countries); }

Future<List<CountryDataEntity>> getCountries() async { final List<CountryDataEntity> countries = <CountryDataEntity>[]; final Box<CountryDataEntity> box = await openDataBox(); countries.addAll(box.values.toList()); return countries; }

Version

  • Platform: iOS, Android, Web
  • Flutter version: [ 2.5.3]
  • Hive version: [2.0.4]
### Tasks
- [ ] https://github.com/isar/hive/issues/1261

Turskyi avatar Nov 25 '21 20:11 Turskyi

If you are retrieving new data from your API you can clear your box and add the new ones.

Future addCountries(List countries) async { final box = await openDataBox(); await box.clear() await box.addAll(countries); }

If the data is not always new but you want to keep track of old data do: Future addCountries(List countries) async { final box = await openDataBox(); final existing = await getCountries(); // This returns the data you have already stored final result = existing.addAll(countries).toSet(); // This removes duplicates await box.addAll(result); }

keezysilencer avatar Dec 16 '21 16:12 keezysilencer