Skip to content

Instantly share code, notes, and snippets.

@kaboc
Last active March 10, 2021 08:13
Show Gist options
  • Select an option

  • Save kaboc/baf651fa30d35d85d110d27216d668ef to your computer and use it in GitHub Desktop.

Select an option

Save kaboc/baf651fa30d35d85d110d27216d668ef to your computer and use it in GitHub Desktop.
Notification between methods without passing a notifier (but with runZoned used instead)
import 'dart:async';
enum ErrorTypes { addUser, saveUser }
final errorHandler = ErrorHandler<ErrorTypes>();
Future<void> main() async {
Process.p1();
await Future<void>.delayed(const Duration(seconds: 1));
Process.p2();
await Future<void>.delayed(const Duration(seconds: 1));
Process.p3();
}
class Process {
static Future<void> p1() async {
print('process1 started');
final result = await errorHandler.scope<bool>(
() async {
errorHandler.setError(ErrorTypes.addUser);
await Future<void>.delayed(const Duration(seconds: 3));
return false;
},
);
print('process1 ended: $result');
}
static Future<void> p2() async {
print('process2 started');
final result = await errorHandler.scope<bool>(
() async {
errorHandler.setError(ErrorTypes.saveUser);
return false;
},
);
print('process2 ended: $result');
}
static Future<void> p3() async {
print('process3 started');
final result = await errorHandler.scope<bool>(
() async => true,
);
print('process3 ended: $result');
}
}
class ErrorHandler<T> {
final _errors = <Zone, T>{};
void _handler(T error) {
print('ERROR! $error');
}
void setError(T error) {
_errors[Zone.current] = error;
}
Future<S> scope<S>(Future<S> Function() process) async {
final result = runZoned(
() async {
final result = await process();
final currentZone = Zone.current;
if (_errors.containsKey(currentZone)) {
_handler(_errors[currentZone]);
}
_errors.remove(currentZone);
return result;
},
);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment