SynchronizedLock extension

Add lock ability to any object.

Then you can simple call on any object.

myObject.synchronized(() async {
  // ...uninterrupted action
});

class MyClass {
  /// Perform a long action that won't be called more than once at a time.
  Future<void> performAction() {
    // Lock at the instance level
    return synchronized(() async {
      // ...uninterrupted action
    });
  }
}

Or you can synchronize at the class level

class MyClass {
  /// Perform a long action that won't be called more than once at a time.
  Future<void> performClassAction() {
    // Lock at the class level
    return runtimeType.synchronized(() async {
      // ...uninterrupted action
    });
  }
}

The lock mechanism is based on identity so beware of potential conflicts (for example using String object).

on

Methods

synchronized<T>(FutureOr<T> computation(), {Duration? timeout}) Future<T>

Available on Object, provided by the SynchronizedLock extension

Runs computation once this object's implicit lock is available, preventing any other call to synchronized on the same object (compared by identity) from running concurrently.