ente/lib/utils/debouncer.dart
Neeraj Gupta f8209ff604 Fix bug in debouncer & increase search tab debounce time
Signed-off-by: Neeraj Gupta <254676+ua741@users.noreply.github.com>
2023-11-28 13:00:35 +05:30

59 lines
1.6 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import "package:photos/models/typedefs.dart";
class Debouncer {
final Duration _duration;
///in milliseconds
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 int? executionIntervalInMilliSeconds;
Timer? _debounceTimer;
Debouncer(this._duration, {this.executionIntervalInMilliSeconds});
final Stopwatch _stopwatch = Stopwatch();
void run(FutureVoidCallback fn) {
bool shouldRunImmediately = false;
if (executionIntervalInMilliSeconds != null) {
// ensure the stop watch is running
_stopwatch.start();
if (_stopwatch.elapsedMilliseconds > executionIntervalInMilliSeconds!) {
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 cancelDebounce() {
if (_debounceTimer != null) {
_debounceTimer!.cancel();
}
}
bool isActive() => _debounceTimer != null && _debounceTimer!.isActive;
ValueNotifier<bool> get debounceActiveNotifier {
return _debounceActiveNotifier;
}
}