import 'dart:async'; import '../../domain/models/hockey_game.dart'; import '../repositories/match_repository.dart'; class MatchDataService { MatchDataService({ required this.repository, this.updateInterval = const Duration(seconds: 1), }) : assert(updateInterval > Duration.zero); final MatchRepository repository; final Duration updateInterval; Timer? _timer; List _matches = []; List _sourceMatches = []; int _sourceCursor = 0; bool _isStarted = false; bool _isDelivering = false; bool _isDisposed = false; Future _writeQueue = Future.value(); void Function(List)? _onMatchesChanged; void Function(Object)? _onError; Future start({ required void Function(List) onMatchesChanged, required void Function(Object) onError, }) async { if (_isStarted) return; _isStarted = true; _onMatchesChanged = onMatchesChanged; _onError = onError; final storedData = await repository.loadStoredData(); _matches = List.of(storedData.matches); _sourceCursor = storedData.sourceCursor; _notifyMatchesChanged(); _sourceMatches = await repository.loadSourceMatches(); await _deliverNextMatch(); if (_sourceCursor < _sourceMatches.length && !_isDisposed) { _timer = Timer.periodic(updateInterval, (_) { unawaited(_deliverNextMatch().catchError(_handleError)); }); } } Future removeMatch(Match match) async { final matchIndex = _matches.indexWhere( (candidate) => identical(candidate, match), ); if (matchIndex == -1) return; final updatedMatches = List.of(_matches)..removeAt(matchIndex); _matches = updatedMatches; _notifyMatchesChanged(); await _persist(updatedMatches, _sourceCursor); } Future _deliverNextMatch() async { if (_isDisposed || _isDelivering || _sourceCursor >= _sourceMatches.length) { _timer?.cancel(); _timer = null; return; } _isDelivering = true; try { final updatedMatches = [..._matches, _sourceMatches[_sourceCursor]]; final nextCursor = _sourceCursor + 1; await _persist(updatedMatches, nextCursor); if (_isDisposed) return; _matches = updatedMatches; _sourceCursor = nextCursor; _notifyMatchesChanged(); if (_sourceCursor >= _sourceMatches.length) { _timer?.cancel(); _timer = null; } } finally { _isDelivering = false; } } Future _persist(List matches, int sourceCursor) { final previousWrite = _writeQueue.catchError((Object _) {}); final nextWrite = previousWrite.then( (_) => repository.saveStoredData(matches, sourceCursor), ); _writeQueue = nextWrite; return nextWrite; } void _notifyMatchesChanged() { _onMatchesChanged?.call(List.unmodifiable(_matches)); } void _handleError(Object error) { _onError?.call(error); } void dispose() { _isDisposed = true; _timer?.cancel(); _timer = null; } }