Created
September 4, 2024 15:54
-
-
Save vincevargadev/0770accf0ca180adb0a372b2506efb21 to your computer and use it in GitHub Desktop.
Dart firstThatResolves
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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