locked_async library
A class which allows running a task with a lock and cancelling the previous task when a new task is run. Useful for file watching, search-as-you-type, etc.
Example:
final task = LockedAsync();
void downloadFile(String url, String filename) {
task.run((state) async {
state.guard();
// Download file from internet
final response = await state.wait(() => http.get(Uri.parse(url)));
await File(filename).writeAsString(response.body);
});
}
downloadFile('https://example.com/file1.txt', 'file1.txt'); // Starts
downloadFile('https://example.com/file2.txt', 'file2.txt'); // Cancels file1, starts file2
Classes
- LockedAsync
- A lock that ensures only one task runs at a time, automatically cancelling the previous task when a new one is started.
- LockedAsyncState
- The state of a task running in an LockedAsync.
Exceptions / Errors
- CancelledException
- An exception thrown when a task is cancelled.