stream property

  1. @override
Stream<Measurement>? get stream
override

The stream of Measurement objects for this StreamProbe. Must be implemented by sub-classes.

Implementation

@override
Stream<Measurement>? get stream {
  late StreamSubscription<battery.BatteryState> subscription;
  late StreamController<Measurement> controller;

  void onData(battery.BatteryState state) async {
    try {
      int level = await battery.Battery().batteryLevel;
      controller.add(
        Measurement.fromData(
          BatteryState.fromBatteryState(level, state),
        ),
      );
    } catch (error) {
      controller.addError(error);
    }
  }

  controller = StreamController<Measurement>(
      onListen: () => subscription.resume(),
      onPause: () => subscription.pause(),
      onResume: () => subscription.resume(),
      onCancel: () => subscription.cancel());

  subscription = battery.Battery().onBatteryStateChanged.listen(
        onData,
        onError: (Object error) => controller.addError(error),
        onDone: () => controller.close(),
      );

  return controller.stream.asBroadcastStream();
}