Stream<ValuePair> calculateHistory(TimeRange range, Duration interval, Rollup rollup)

Source

Stream<ValuePair> calculateHistory(TimeRange range,
  Duration interval,
  Rollup rollup) async* {
  if (interval.inMilliseconds <= 0) {
    yield* fetchHistoryData(range);
    return;
  }

  int lastTimestamp = -1;
  int totalTime = 0;

  ValuePair result;

  await for (ValuePair pair in fetchHistoryData(range)) {
    rollup.add(pair.value);
    if (lastTimestamp != -1) {
      totalTime += pair.time.millisecondsSinceEpoch - lastTimestamp;
    }
    lastTimestamp = pair.time.millisecondsSinceEpoch;
    if (totalTime >= interval.inMilliseconds) {
      totalTime = 0;
      result = new ValuePair(
        new DateTime.fromMillisecondsSinceEpoch(
          lastTimestamp
        ).toIso8601String(),
        rollup.value
      );
      yield result;
      result = null;
      rollup.reset();
    }
  }

  if (result != null) {
    yield result;
  }
}