Last active
May 7, 2021 10:52
-
-
Save davidmigloz/8b6fc691a7da3c55cd3e1fc1a05df40b 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(Duration(seconds: 5), tasks: [ | |
myTask1, | |
myTask2, | |
myTask3, | |
]); | |
print("Result: $res Execution time: ${stopwatch.elapsed.inSeconds}sec"); | |
} | |
typedef Future<T> Task<T>(); | |
Future<List<T>> runWithMinDuration<T>(Duration minDuration, | |
{required List<Task<T>> tasks}) 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