Question

Consider I have code like this:

import 'dart:async';

foo() {
  print('foo');
}

bar() {
  print('bar');
}

void main() {
  runZoned(() {
    new Timer(const Duration(seconds: 1), foo);
    new Timer(const Duration(seconds: 2), bar);
  });
}

How can I know when all the async work inside a Zone is completed? That is, is it possible to know when all the async methods (either via timer, future, etc) that were registered within a zone are complete?

Was it helpful?

Solution

Initially zones did have an "onDone" callback. (See a usage in an old test here). However we discovered that it is too hard to keep track of outstanding callbacks. For example: future.then(callback) registers a callback, but there is absolutely no guarantee that this callback will ever be invoked.

In fact, it is quite common that futures are never completed. Zones, themselves, contribute to this: when an error originates in a zone that has an error-handler the error will never leave the zone. That means that future-chains outside the zone won't be completed (neither with a value nor the error that got intercepted by the zone).

TL;DR: we had onDone on zones but removed it because it was impractical.

OTHER TIPS

I tried to find this out too.
It seems the async queue is not implemented in Dart but managed by the VM.
The isolate running the Dart code gets a message to run the registered callbacks.

It might be possible to create a derived Zone that does some bookkeeping about scheduled tasks (add to its own queue before submitting the call to the default implementation and also wrapping the callback to get notified when the callback gets called, to remove it from the queue).

I hope someone comes up with a better answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top