selfprivacy.org.app/lib/logic/cubit/metrics/metrics_cubit.dart
NaiJi 68f34dc7b7 feat(metrics): Implement disk usage metrics
- Refactor metrics_cubit
- Implement fallback to legacy when less than 20 dots
2024-08-06 18:45:18 +03:00

60 lines
1.4 KiB
Dart

import 'dart:async';
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:selfprivacy/logic/common_enum/common_enum.dart';
import 'package:selfprivacy/logic/cubit/metrics/metrics_repository.dart';
import 'package:selfprivacy/logic/models/metrics.dart';
part 'metrics_state.dart';
class MetricsCubit extends Cubit<MetricsState> {
MetricsCubit() : super(const MetricsLoading(Period.day));
final MetricsRepository repository = MetricsRepository();
Timer? timer;
@override
Future<void> close() {
closeTimer();
return super.close();
}
void closeTimer() {
if (timer != null && timer!.isActive) {
timer!.cancel();
}
}
void changePeriod(final Period period) async {
closeTimer();
emit(MetricsLoading(period));
load(period);
}
void restart() async {
load(state.period);
}
void load(final Period period) async {
try {
final MetricsStateUpdate newStateUpdate =
await repository.getRelevantServerMetrics(period);
int duration = newStateUpdate.nextCheckInSeconds;
if (duration <= 0) {
duration = state.period.stepPeriodInSeconds;
}
timer = Timer(
Duration(seconds: duration),
() => load(period),
);
emit(newStateUpdate.newState);
} on StateError {
print('Tried to emit metrics when cubit is closed');
}
}
}