start method

Stream<Event> start({
  1. bool onlyNew = false,
  2. int? interval,
  3. DateTime? after,
})

Implementation

Stream<Event> start({bool onlyNew = false, int? interval, DateTime? after}) {
  if (_timer != null) {
    throw Exception('Polling already started.');
  }

  if (after != null) {
    after = after.toUtc();
  }

  _controller = StreamController<Event>();

  void handleEvent(http.Response response) {
    interval ??= int.parse(response.headers['x-poll-interval']!);

    if (response.statusCode == 304) {
      return;
    }

    _lastFetched = response.headers['ETag'];

    final json = List<Map<String, dynamic>>.from(jsonDecode(response.body));

    if (!(onlyNew && _timer == null)) {
      for (final item in json) {
        final event = Event.fromJson(item);

        if (after == null
            ? false
            : event.createdAt!.toUtc().isBefore(after)) {
          continue;
        }

        if (handledEvents.contains(event.id)) {
          continue;
        }

        handledEvents.add(event.id);

        _controller!.add(event);
      }
    }

    _timer ??= Timer.periodic(Duration(seconds: interval!), (timer) {
      final headers = <String, String>{};

      if (_lastFetched != null) {
        headers['If-None-Match'] = _lastFetched ?? '';
      }

      github.request('GET', path, headers: headers).then(handleEvent);
    });
  }

  final headers = <String, String>{};

  if (_lastFetched != null) {
    headers['If-None-Match'] = _lastFetched ?? '';
  }

  github.request('GET', path, headers: headers).then(handleEvent);

  return _controller!.stream;
}