Add background sync runner and rejected-sync UX
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:relationship_saver/features/sync/sync_coordinator.dart';
|
||||
|
||||
typedef SyncNowRunner = Future<SyncRunResult> Function();
|
||||
|
||||
/// Coordinates auto-triggered sync calls with cooldown and concurrency guards.
|
||||
class SyncAutoTriggerController {
|
||||
SyncAutoTriggerController({
|
||||
required SyncNowRunner syncNow,
|
||||
required DateTime Function() now,
|
||||
this.minimumInterval = const Duration(minutes: 3),
|
||||
}) : _syncNow = syncNow,
|
||||
_now = now;
|
||||
|
||||
final SyncNowRunner _syncNow;
|
||||
final DateTime Function() _now;
|
||||
final Duration minimumInterval;
|
||||
|
||||
bool _running = false;
|
||||
DateTime? _lastTriggeredAt;
|
||||
|
||||
@visibleForTesting
|
||||
bool get isRunning => _running;
|
||||
|
||||
@visibleForTesting
|
||||
DateTime? get lastTriggeredAt => _lastTriggeredAt;
|
||||
|
||||
/// Triggers `syncNow` when not already running and outside cooldown window.
|
||||
Future<bool> trigger({bool ignoreCooldown = false}) async {
|
||||
if (_running) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final DateTime now = _now();
|
||||
final DateTime? last = _lastTriggeredAt;
|
||||
if (!ignoreCooldown &&
|
||||
last != null &&
|
||||
now.difference(last) < minimumInterval) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_running = true;
|
||||
_lastTriggeredAt = now;
|
||||
try {
|
||||
await _syncNow();
|
||||
return true;
|
||||
} catch (_) {
|
||||
return true;
|
||||
} finally {
|
||||
_running = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user