fetchNews method

Future<List<NewsMarker>> fetchNews({
  1. required LatLngBounds bounds,
  2. String query = 'news',
  3. int maxResults = 250,
  4. String timeSpan = '24h',
  5. bool forceRefresh = false,
})

Fetch news markers within the specified bounds with debouncing and caching.

Implementation

Future<List<NewsMarker>> fetchNews({
  required LatLngBounds bounds,
  String query = 'news',
  int maxResults = 250,
  String timeSpan = '24h',
  bool forceRefresh = false,
}) async {
  // If bounds are covered by cache and not forcing refresh, return filtered cache
  if (!forceRefresh && isBoundsCovered(bounds)) {
    debugPrint('Using cached news data');
    return getMarkersInBounds(bounds);
  }

  _debounceTimer?.cancel();

  final completer = Completer<List<NewsMarker>>();

  _debounceTimer = Timer(_debounceDuration, () async {
    try {
      final now = DateTime.now();
      if (_lastFetchTime != null) {
        final elapsed = now.difference(_lastFetchTime!);
        if (elapsed < _minFetchInterval) {
          final waitTime = _minFetchInterval - elapsed;
          await Future.delayed(waitTime);
        }
      }
      _lastFetchTime = now;

      final markers = await _performFetch(
        bounds: bounds,
        query: query,
        maxResults: maxResults,
        timeSpan: timeSpan,
      );

      // Update cache.

      _cachedMarkers.clear();
      _cachedMarkers.addAll(markers);
      _cachedBounds = bounds;
      _cacheTime = DateTime.now();
      debugPrint('Cached ${markers.length} news markers');

      completer.complete(markers);
    } catch (e) {
      completer.completeError(e);
    }
  });

  return completer.future;
}