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!'));
}
_isCompleting = true;
if (isCompleted) {
_isCompleting = false;
return Sync.err(Err('SafeCompleter<$T> is already completed!'));
}
// `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;
});
}