compute<R> method

Future<R> compute<R>(
  1. FutureOr<R> task()
)

Run task on a worker isolate and give its result, so the server can answer other requests while it runs. Use it for heavy CPU work: a PDF, an image, a big JSON file. Tasks run on a small pool of workers (AppConfig.computeWorkers). More tasks wait in line, first come first served. An error of the task is thrown here, with its stack trace.

task runs in another isolate. It can only use values that can be sent between isolates: numbers, strings, lists, maps, plain objects. It can not use the state of the app: the IoC container, a database pool, a cache store or an open socket are not there. Read what it needs first, and pass it in. A closure also holds the other variables of the function it is made in. When one of them can not be sent (like a database connection), the task fails with an ArgumentError. Make the task in a small top-level or static function to be safe.

It works without a server too (a command, a test, a queue job). Inside a worker, a nested compute runs the task in that same worker.

List<int> pdf = await Dox().compute(() => buildPdf(order.toJson()));

Implementation

Future<R> compute<R>(FutureOr<R> Function() task) {
  return ComputePool.instance.run(task);
}