Last active
May 7, 2021 10:43
-
-
Save davidmigloz/bdc706dad0f1905ec13d18082e30476a to your computer and use it in GitHub Desktop.
runWithMinDuration
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
void main() async { | |
final stopwatch = Stopwatch()..start(); | |
final res = await runWithMinDuration([ | |
myTask1, | |
myTask2, | |
myTask3, | |
], minDuration: Duration(seconds: 5)); | |
print("Result: $res Execution time: ${stopwatch.elapsed.inSeconds}sec"); | |
} | |
typedef Future<T> Task<T>(); | |
Future<List<T>> runWithMinDuration<T>(List<Task<T>> tasks, | |
{Duration minDuration: const Duration(seconds: 5)}) async { | |
final fMinDur = Future.delayed(minDuration); | |
List<Future<T>> fTasks = tasks.map((t) => t()).toList(growable: false); | |
return (await Future.wait([fMinDur, ...fTasks])).sublist(1).cast(); | |
} | |
Future<int> myTask1() async { | |
await Future.delayed(Duration(seconds: 1)); | |
return 1; | |
} | |
Future<int> myTask2() async { | |
await Future.delayed(Duration(seconds: 2)); | |
return 2; | |
} | |
Future<int> myTask3() async { | |
await Future.delayed(Duration(seconds: 3)); | |
return 3; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment