Skip to content

Instantly share code, notes, and snippets.

@vincevargadev
Created September 4, 2024 15:54
Show Gist options
  • Save vincevargadev/0770accf0ca180adb0a372b2506efb21 to your computer and use it in GitHub Desktop.
Save vincevargadev/0770accf0ca180adb0a372b2506efb21 to your computer and use it in GitHub Desktop.
Dart firstThatResolves
import 'dart:async';
extension FutureX<T> on Future<T> {
/// This function accepts two functions returning a future,
/// and returns whichever function resolves successfully first.
///
/// Can be used in case one of the functions may fail
/// even under normal circumstances as long as the other succeeds
/// (so at least one of them should succeed).
///
/// If both functions return an error, this static method will
/// use the second error.
static Future<T> firstThatResolves<T>(
Future<T> Function() a,
Future<T> Function() b,
) {
final completer = Completer<T>();
var aCompleted = false;
var bCompleted = false;
a().then((t) {
aCompleted = true;
if (bCompleted) return;
completer.complete(t);
}).catchError((Object e, StackTrace st) {
aCompleted = true;
if (bCompleted && completer.isCompleted) return;
completer.completeError(e, st);
});
b().then((t) {
bCompleted = true;
if (aCompleted) return;
completer.complete(t);
}).catchError((Object e, StackTrace st) {
bCompleted = true;
if (aCompleted) return;
completer.completeError(e, st);
});
return completer.future;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment