Debounce drift table updates

This can be a problem during the very first sync, where all exercises, units,
ingredients are loaded and rebuild on every new data point.
This commit is contained in:
Roland Geider
2026-06-25 20:02:30 +02:00
parent eb2bb0f9ef
commit 9122cc1a1e
2 changed files with 18 additions and 3 deletions

View File

@@ -165,6 +165,7 @@ class ExerciseRepository {
late StreamController<ExerciseState> controller;
final subs = <StreamSubscription>[];
Timer? emitTimer;
void emit() {
if (exerciseRows == null ||
@@ -303,6 +304,14 @@ class ExerciseRepository {
controller.add(ExerciseState(exercises));
}
// A full rebuild runs on every table update. During the initial sync many
// updates arrive in bursts, so coalesce them into a single rebuild once
// they settle instead of reassembling the whole catalog hundreds of times.
void scheduleEmit() {
emitTimer?.cancel();
emitTimer = Timer(const Duration(milliseconds: 200), emit);
}
controller = StreamController<ExerciseState>(
onListen: () {
void addSub<T>(Stream<T> source, void Function(T) assign) {
@@ -310,7 +319,7 @@ class ExerciseRepository {
source.listen(
(value) {
assign(value);
emit();
scheduleEmit();
},
onError: controller.addError,
),
@@ -334,6 +343,7 @@ class ExerciseRepository {
addSub(_db.select(_db.exerciseCommentTable).watch(), (v) => comments = v);
},
onCancel: () async {
emitTimer?.cancel();
for (final s in subs) {
await s.cancel();
}

View File

@@ -20,6 +20,7 @@ import 'package:collection/collection.dart';
import 'package:drift/drift.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:logging/logging.dart';
import 'package:stream_transform/stream_transform.dart';
import 'package:wger/database/powersync/database.dart';
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/models/nutrition/ingredient_weight_unit.dart';
@@ -40,6 +41,10 @@ class NutritionRepository {
NutritionRepository(this._db);
/// Coalesces bursts of Drift table updates (e.g. during the initial sync) so
/// the heavy per-emission hydration runs once they settle, not on every write.
static const _hydrationDebounce = Duration(milliseconds: 200);
// --- Plans ---
/// Streams all nutritional plans from the local PowerSync-backed Drift table.
@@ -113,7 +118,7 @@ class NutritionRepository {
OrderingTerm.asc(_db.mealTable.time),
]);
return query.watch().map(_hydrateMeals);
return query.watch().debounce(_hydrationDebounce).map(_hydrateMeals);
}
/// Collapses cross-joined rows into hydrated [Meal]s with their child items.
@@ -268,7 +273,7 @@ class NutritionRepository {
),
])..orderBy([OrderingTerm(expression: _db.logItemTable.datetime)]);
return query.watch().map(_hydrateLogs);
return query.watch().debounce(_hydrationDebounce).map(_hydrateLogs);
}
/// Collapses the cross-joined rows into hydrated [LogItem]s.