Line data Source code
1 : import 'dart:async';
2 : import 'package:flutter/foundation.dart';
3 : import '../debouncer_config.dart';
4 : import 'debounce_strategy.dart';
5 :
6 : /// Fires the action on **both** the leading and trailing edge.
7 : ///
8 : /// - Leading fire: immediate on first call.
9 : /// - Trailing fire: once more after [DebouncerConfig.delay] has passed
10 : /// since the last call — but only if there were additional calls after
11 : /// the initial leading fire.
12 : ///
13 : /// Timeline:
14 : /// ```
15 : /// calls: --A--B--C-----------
16 : /// fires: --A----------------C
17 : /// ```
18 : class BothEdgeStrategy extends DebouncerStrategy {
19 1 : const BothEdgeStrategy();
20 :
21 1 : @override
22 : void execute(
23 : VoidCallback action,
24 : DebouncerConfig config,
25 : Timer? currentTimer,
26 : void Function(Timer?) updateTimer,
27 : ) {
28 0 : final isIdle = currentTimer == null || !currentTimer.isActive;
29 :
30 0 : currentTimer?.cancel();
31 :
32 : // Always schedule a trailing fire.
33 4 : updateTimer(Timer(config.delay, () {
34 1 : action();
35 1 : updateTimer(null);
36 : }));
37 :
38 : // Leading fire on first call only.
39 : if (isIdle) {
40 1 : action();
41 : }
42 : }
43 : }
|