async_mutex.dart 624 B

123456789101112131415161718192021
  1. import 'dart:async';
  2. /// Async mutex to guarantee actions are performed sequentially and do not interleave
  3. class AsyncMutex {
  4. Future _running = Future.value(null);
  5. int _enqueued = 0;
  6. get enqueued => _enqueued;
  7. /// Execute [operation] exclusively, after any currently running operations.
  8. /// Returns a [Future] with the result of the [operation].
  9. Future<T> run<T>(Future<T> Function() operation) {
  10. final completer = Completer<T>();
  11. _enqueued++;
  12. _running.whenComplete(() {
  13. _enqueued--;
  14. completer.complete(Future<T>.sync(operation));
  15. });
  16. return _running = completer.future;
  17. }
  18. }