Skip to content

Instantly share code, notes, and snippets.

@SteveAlexander
Last active March 18, 2021 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveAlexander/868387d124156869eff7de5f8892d596 to your computer and use it in GitHub Desktop.
Save SteveAlexander/868387d124156869eff7de5f8892d596 to your computer and use it in GitHub Desktop.
interrupting in a zone
import 'dart:async';
void main(List<String> arguments) {
var stop = false;
final checkShouldStop = () {
if (stop) {
throw StopException();
}
};
runZoned(
run,
zoneSpecification: ZoneSpecification(
registerCallback: <R>(self, parent, zone, f) {
checkShouldStop();
return f;
},
registerUnaryCallback: <R, T>(self, parent, zone, f) {
checkShouldStop();
return f;
},
registerBinaryCallback: <R, T, U>(self, parent, zone, f) {
checkShouldStop();
return f;
},
),
);
// Cause an interrupt after some time
Future.delayed(Duration(milliseconds: 750), () {
stop = true;
});
}
Future<void> run() async {
print('run');
await something(1, 2, 3, 4);
print('done something');
final output = await slowlyMakeString(['foo', 'bar', 'baz']);
print(output);
}
Future<String> slowlyMakeString(List<String> args) async {
final needToCleanUp = <String>[];
try {
print('slowlyMakeString');
final output = StringBuffer();
for (final arg in args) {
print('awaiting delay');
await Future.delayed(Duration(milliseconds: 500));
output.write(arg);
needToCleanUp.add(arg);
}
return output.toString();
} on StopException {
print('cleaning up: $needToCleanUp');
rethrow;
}
}
Future<void> something(int a, int b, int c, int d) async {
print('doing something');
return;
}
class StopException implements Exception {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment