resolve method
Safely resolves the completer with the outcome of a Resolvable.
If the completer is already completed or is in the process of completing, this method will return an Err and have no effect.
Implementation
Resolvable<T> resolve(Resolvable<T> resolvable) {
if (_isCompleting) {
return Sync.err(Err('SafeCompleter<$T> is already resolving!'));
}
// Check terminal state directly (do NOT read `isCompleted` here — that
// now includes the `_isCompleting` flag we're about to set below, which
// would always make this check trip).
if (_completer.isCompleted || _value.isSome()) {
return Sync.err(Err('SafeCompleter<$T> is already completed!'));
}
_isCompleting = true;
// `ifOk` and `ifErr` are used to handle the two possible outcomes of the
// resolvable, ensuring the completer is correctly handled in both cases.
return resolvable.ifOk((_, ok) {
final okValue = ok.unwrap();
_value = Some(okValue);
_completer.complete(okValue);
}).ifErr((_, err) {
_completer.completeError(err);
}).whenComplete((_) {
// Ensure the lock is always released.
_isCompleting = false;
return resolvable;
});
}