start method
Implementation
Future<void> start(TripConfig config, Stream<Location> source) async {
// Load persisted state first to decide if we can restore
TripState? restored;
if (_store != null) {
restored = await _store!.load();
}
final shouldRestore = restored != null &&
!restored.ended &&
(config.tripId == null || config.tripId == restored.tripId);
// If we are NOT restoring, we clean up any existing session fully
if (!shouldRestore) {
stop();
} else {
// If restoring, just cancel the previous stream so we can re-bind
await _subscription?.cancel();
_subscription = null;
}
_config = config;
_pendingStartLocation = null;
_lastUpdateAt = null;
_lastDeviationAt = null;
_lastStationaryAt = null;
_lastPersistAt = null;
_dwellEmitted = false;
if (shouldRestore) {
_state = restored;
} else {
final tripId = config.tripId ?? _generateTripId();
_state = TripState(
tripId: tripId,
createdAt: DateTime.now().toUtc(),
startedAt: null,
startLocation: null,
lastLocation: null,
distanceMeters: 0,
idleSeconds: 0,
maxSpeedKph: 0,
started: false,
ended: false,
);
await _persistState(force: true);
}
_subscription = source.listen(_handleLocation);
}