watchMetrics method
Implementation
@override
Stream<SystemMetrics> watchMetrics({Duration interval = const Duration(seconds: 1)}) {
late StreamController<SystemMetrics> controller;
Timer? timer;
void tick() async {
try {
final metrics = await getSystemMetrics();
if (!controller.isClosed) {
controller.add(metrics);
}
} catch (e, st) {
if (!controller.isClosed) {
controller.addError(e, st);
}
}
}
controller = StreamController<SystemMetrics>.broadcast(
onListen: () {
tick(); // immediate first capture
timer = Timer.periodic(interval, (_) => tick());
},
onCancel: () {
timer?.cancel();
timer = null;
},
);
return controller.stream;
}