Created
April 20, 2022 20:56
-
-
Save bradleybauer/d1671724da75c236dddff9e4ad8176c3 to your computer and use it in GitHub Desktop.
This file contains 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
class ChainProcessor { | |
var arg = ''; | |
var didUpdateArg = false; | |
bool isComputing = false; | |
void _computation() { | |
// do stuff | |
} | |
void chain() async { | |
var argcopy = arg; | |
print('Computation('+argcopy+') start'); | |
// do computation | |
await Future.delayed(const Duration(seconds: 3), _computation).then((x) { | |
print('Computation(' + argcopy + ') done'); | |
// when done check if need to compute again | |
if (didUpdateArg) { | |
didUpdateArg = false; | |
chain(); | |
} | |
isComputing = false; | |
}); | |
} | |
void compute(nextarg) { | |
arg = nextarg; | |
if (!isComputing) { | |
isComputing = true; | |
chain(); | |
} else { | |
didUpdateArg = true; | |
} | |
} | |
} | |
Future<void> main() async { | |
final processor = ChainProcessor(); | |
// initial computation request | |
processor.compute('1'); | |
// new computation requests with different arguments | |
Future.delayed(const Duration(seconds: 1), () => processor.compute('2')); | |
Future.delayed(const Duration(milliseconds: 1500), () => processor.compute('3')); | |
// but only the argument in the most recent request is computed | |
Future.delayed(const Duration(milliseconds: 1600), () => processor.compute('4')); | |
// when no computation is being done, more chains can be started | |
Future.delayed(const Duration(seconds: 11), () => processor.compute('5')); | |
Future.delayed(const Duration(seconds: 12), () => processor.compute('6')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment