newPoller<T> method

Stream<T> newPoller<T>(
  1. Future<T> callback(),
  2. Duration interval
)

Creates a Stream that polls a callback at a specified interval.

Implementation

Stream<T> newPoller<T>(
  Future<T> Function() callback,
  Duration interval,
) {
  final controller = StreamController<T>.broadcast();
  Timer? timer;

  Future<void> poll() async {
    try {
      final result = await callback();
      controller.add(result);
    } catch (e) {
      controller.addError(e);
    }
  }

  controller.onListen = () {
    timer = Timer.periodic(interval, (_) => poll());
  };

  controller.onCancel = () {
    timer?.cancel();
    controller.close();
  };

  return controller.stream;
}