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 equality (==/hashCode), not identity, so
any two objects that compare equal share the same lock. Beware of potential
conflicts: the lock cache is global to the process, so value types such as
String or int are effectively a namespace shared with every other
library in the application. Lock on a private instance
(final _lock = Object();) when isolation matters.
- on
Methods
-
synchronized<
T> (FutureOr< T> computation(), {Duration? timeout}) → Future<T> -
Available on Object, provided by the SynchronizedLock extension
Runscomputationonce this object's implicit lock is available, preventing any other call to synchronized on an equal object (compared with==) from running concurrently.