1

How an I spawn an Isolate blocking on an async function in Flutter?

I tried dart:cli's waitFor function, but it seems that dart:cli does not work together with Flutter.

porton
  • 5,214
  • 11
  • 47
  • 95
  • There is no supported way to block on an `async` function. Why would you need an `Isolate` to block anyway? Why can't you just `await` the `Future`? – jamesdlin Sep 23 '22 at 15:33
  • @jamesdlin because `Isolate.spawn` spawns a non-async function and therefore I can't in it `await` the `Future`. – porton Sep 23 '22 at 15:47

1 Answers1

2

There is no supported way to block on an async function.

You shouldn't need an Isolate to block anyway. Each Isolate has its own event loop and can just await the Future returned by your asynchronous function before calling Isolate.exit. For example:

import 'dart:isolate';

void foo(SendPort p) async {
  for (var i = 0; i < 5; i += 1) {
    await Future.delayed(const Duration(seconds: 1));
    print('foo: $i');
  }

  Isolate.exit(p);
}

void main() async {
  var p = ReceivePort();
  await Isolate.spawn(foo, p.sendPort);
  print('Isolate spawned.');

  // Wait for the Isolate to complete.
  await p.first;
  print('Done');
}

which prints:

Isolate spawned.
foo: 0
foo: 1
foo: 2
foo: 3
foo: 4
Done
jamesdlin
  • 81,374
  • 13
  • 159
  • 204