Skip to content

Instantly share code, notes, and snippets.

@dumazy
Created November 8, 2024 09:33
Show Gist options
  • Save dumazy/167ed9491a729907e0b544ce1c1485cd to your computer and use it in GitHub Desktop.
Save dumazy/167ed9491a729907e0b544ce1c1485cd to your computer and use it in GitHub Desktop.
Example of AsyncCache for preventing concurrent execution.
import 'package:async/async.dart';
/// Example of how AsyncCache can prevent concurrent execution.
void main() async {
// Call _execute every second.
// In a real use case, multiple triggers can call [_execute]
// e.g: start up, user interaction, connectivity change, etc
for (int i = 0; i < 10; i++) {
_execute(i);
await Future.delayed(Duration(seconds: 1));
}
}
final _cache = AsyncCache.ephemeral();
Future<void> _execute(int index) async {
print('Attempt: $index');
/// Execution takes 3 seconds
_cache.fetch(() async {
print('Executing: $index');
await Future.delayed(Duration(seconds: 3));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment