ente/mobile/lib/utils/debouncer.dart
Neeraj Gupta 7621041ce0 Revert "[mob] Fix exif time parsing (#4985)"
This reverts commit 5b17711b55e9e8995454121e3a209ee5e8c9b3c1, reversing
changes made to 85bf3eebcb5ac197ce6a5901cbc8db1d03be0113.
2025-02-11 18:27:17 +05:30

72 lines
2.0 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import "package:photos/models/typedefs.dart";
///Do not forget to cancel the debounce's timer using [cancelDebounceTimer]
///when the debouncer is no longer needed
class Debouncer {
final Duration _duration;
final ValueNotifier<bool> _debounceActiveNotifier = ValueNotifier(false);
/// If executionIntervalInSeconds is not null, then the debouncer will execute the
/// current callback it has in run() method repeatedly in the given interval.
/// This is useful for example when you want to execute a callback every 5 seconds
final Duration? executionInterval;
Timer? _debounceTimer;
final bool leading;
Debouncer(this._duration, {this.executionInterval, this.leading = false});
final Stopwatch _stopwatch = Stopwatch();
void run(FutureVoidCallback fn) {
if (leading && !isActive()) {
_stopwatch.stop();
_stopwatch.reset();
fn();
_debounceTimer = Timer(_duration, () {
_debounceActiveNotifier.value = false;
});
_debounceActiveNotifier.value = true;
return;
}
bool shouldRunImmediately = false;
if (executionInterval != null) {
// ensure the stop watch is running
_stopwatch.start();
if (_stopwatch.elapsedMilliseconds > executionInterval!.inMilliseconds) {
shouldRunImmediately = true;
_stopwatch.stop();
_stopwatch.reset();
}
}
if (isActive()) {
_debounceTimer!.cancel();
}
_debounceTimer =
Timer(shouldRunImmediately ? Duration.zero : _duration, () async {
_stopwatch.stop();
_stopwatch.reset();
await fn();
_debounceActiveNotifier.value = false;
});
_debounceActiveNotifier.value = true;
}
void cancelDebounceTimer() {
if (_debounceTimer != null) {
_debounceTimer!.cancel();
}
}
bool isActive() => _debounceTimer != null && _debounceTimer!.isActive;
ValueNotifier<bool> get debounceActiveNotifier {
return _debounceActiveNotifier;
}
}