46 lines
1.6 KiB
Dart
46 lines
1.6 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import '../../features/rides/ride_state_machine.dart';
|
|
import 'sync_manager.dart';
|
|
import 'sync_providers.dart';
|
|
|
|
/// External observer listening for ride state machine transitions.
|
|
/// Automatically enqueues completed rides into the synchronization pipeline
|
|
/// without modifying or blocking the frozen RideStateMachine.
|
|
class SyncObserver {
|
|
final SyncManager _syncManager;
|
|
int? _lastEnqueuedRideId;
|
|
|
|
SyncObserver(this._syncManager);
|
|
|
|
/// Called when the RideStateMachine state changes in Riverpod
|
|
void onRideSessionChanged(RideSession? previous, RideSession next) {
|
|
// Detect transition into finished state
|
|
final wasFinished = previous?.state == RideState.finished;
|
|
final isFinished = next.state == RideState.finished;
|
|
final completedRideId = next.dbId;
|
|
|
|
if (!wasFinished && isFinished && completedRideId != null) {
|
|
if (_lastEnqueuedRideId != completedRideId) {
|
|
_lastEnqueuedRideId = completedRideId;
|
|
debugPrint('[SyncObserver] Ride #$completedRideId completed, enqueuing to SyncManager');
|
|
_syncManager.enqueueRide(completedRideId);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Riverpod provider establishing the active SyncObserver listener
|
|
final syncObserverProvider = Provider<SyncObserver>((ref) {
|
|
final manager = ref.watch(syncManagerProvider);
|
|
final observer = SyncObserver(manager);
|
|
|
|
// External, non-invasive observation of the frozen RideStateMachine
|
|
ref.listen<RideSession>(
|
|
rideStateMachineProvider,
|
|
(previous, next) => observer.onRideSessionChanged(previous, next),
|
|
);
|
|
|
|
return observer;
|
|
});
|