Created
November 8, 2024 09:33
-
-
Save dumazy/167ed9491a729907e0b544ce1c1485cd to your computer and use it in GitHub Desktop.
Example of AsyncCache for preventing concurrent execution.
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 '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