notified method
Register to be notified, returning a future and cancellation function.
If a permit is available, the future completes immediately and consumes one permit. Otherwise, registers a waiter until notifyOne/notifyAll is called or the operation is canceled.
Returns:
future
: Completes when notified or fails if canceled/closedcancel
: Function to cancel the notification (optional)
Example:
final (future, cancel) = notify.notified();
// Option 1: Wait indefinitely
await future;
// Option 2: Cancel if taking too long
Timer(Duration(seconds: 10), cancel);
await future.catchError((e) => print('Canceled or timed out'));
Implementation
(Future<void>, void Function()) notified() {
if (_closed) {
return (Future<void>.error(StateError('Notify.disconnected')), () {});
}
if (_permits > 0) {
_permits--;
return (Future.value(), () {});
}
final c = Completer<void>();
_waiters.add(c);
void cancel() {
if (!c.isCompleted) {
_waiters.remove(c);
c.completeError(StateError('Notify.canceled'));
}
}
return (c.future, cancel);
}