Created
July 15, 2024 14:32
-
-
Save lopo12123/515e6de3232557b2bc5818375d3c3961 to your computer and use it in GitHub Desktop.
BadFL Example Code (helper/throttle)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
class BadThrottler { | |
/// default action to be called when the throttler is called without a action | |
final FutureOr<void> Function()? defaultAction; | |
bool _running = false; | |
BadThrottler({this.defaultAction}); | |
Future<void> call([FutureOr<void> Function()? action]) async { | |
if (_running) return; | |
assert( | |
action != null || defaultAction != null, | |
'can only call throttler without action when defaultAction is provided', | |
); | |
_running = true; | |
await (action ?? defaultAction)!(); | |
_running = false; | |
} | |
} | |
void main() async { | |
final throttler = BadThrottler(defaultAction: () async { | |
await Future.delayed(const Duration(milliseconds: 500)); | |
print('default action'); | |
}); | |
// call the default action | |
throttler(); | |
// this call will be ignored | |
throttler(() async { | |
print('hello'); | |
}); | |
// call with a custom action | |
await Future.delayed(const Duration(seconds: 1)); | |
throttler(() async { | |
print('hello again'); | |
}); | |
} | |
// Output: | |
// default action | |
// hello again |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment