在DART中,有没有办法把S在Zone米内创造的Future
英尺都捕捉到?
目前,我被迫手动将它们全部捕获,但这似乎很容易忘记这样做.因此,如果可能的话,我想将其自动化.
在下面的示例代码中,我希望捕获someAsyncWork
,这样就可以在Main runPluginCode
运行后等待它.
import 'dart:async';
Future<void> main() async {
print('Run plugin code');
await runZoned(
() async {
runPluginCode();
final tasks = Zone.current['tasks'] as List<Future>;
await Future.wait(tasks);
},
zoneValues: {
'taskId': 123,
'tasks': <Future>[],
},
);
print('Exit plugin code');
}
void runPluginCode() {
// External QuickJS script that only has sync API methods
// but they may call into async functions that need to be awaited before
// the plugin code ends
someTask();
}
void someTask() {
print('performing task');
// I don't want manually do this everywhere
// final tasks = Zone.current['tasks'] as List<Future>;
// tasks.add(someAsyncWork());
someAsyncWork();
}
Future<void> someAsyncWork() async {
await Future.delayed(const Duration(milliseconds: 200));
final taskId = Zone.current['taskId'] as int;
print('async work completed for task $taskId did I complete inside the plugin code???');
}
我相信这应该是可能的,当使用自定义ZoneSpecification
我试过了,但一点运气都没有.
zoneSpecification: ZoneSpecification(
run: <R>(self, parent, zone, f) {
final task = parent.run(zone, f);
if (task is Future) {
(zone['tasks'] as List<Future>).add(task);
}
return task;
},
runUnary: <R, T>(self, parent, zone, f, arg) {
final task = parent.runUnary(zone, f, arg);
if (task is Future) {
(zone['tasks'] as List<Future>).add(task);
}
return task;
},
runBinary: <R, T1, T2>(self, parent, zone, f, arg1, arg2) {
final task = parent.runBinary(zone, f, arg1, arg2);
if (task is Future) {
(zone['tasks'] as List<Future>).add(task);
}
return task;
},
)