stopWatchStream method

Stream<int> stopWatchStream()

stop watch stream

Implementation

Stream<int> stopWatchStream() {
  StreamController<int>? streamController;
  Duration timerInterval = const Duration(milliseconds: 10);
  int counter = startWithTenMilliseconds ?? 0;

  /// Private
  _tick(_) {
    counter++;
    streamController?.add(counter);
  }

  _startTimer() {
    timer ??= Timer.periodic(timerInterval, _tick);
  }

  _stopTimer() {
    if (timer != null) {
      timer?.cancel();
      timer = null;
      counter = startWithTenMilliseconds ?? 0;
      streamController?.close();
    }
  }

  _pauseTimer() {
    if (timer != null) {
      timer?.cancel();
    }
  }

  _resumeTimer() {
    if (timer != null) {
      timer = Timer.periodic(timerInterval, _tick);
    }
  }

  streamController = StreamController<int>(
    onListen: _startTimer,
    onPause: _pauseTimer,
    onResume: _resumeTimer,
    onCancel: _stopTimer,
  );

  return streamController.stream;
}