Dart / Flutter: async behaviour of an Isolate's top level function

Issue

Aye Aye good people,
I’m experiencing a weird behavior

when using the top level function of an isolate asynchronously;

you can find example code HERE, but in short

as top level function of an isolate this works:

String _syncHandle(int data) {
  return 'done';
}

and this doesn’t:

Future<String> _syncHandle(int data) async {
  return 'done';
}

can anybody explain me why?

(or if should work, why isn’t doing so in my code?)

thank you in advance

Francesco

[edit: just noticed that a similar question has been asked,

nevertheless it is still unanswered
Call async function from Isolate function,

plus issue open on github ]

Solution

forgot to update this :/
if you look at the code linked in the question

isolates_logging/lib/provider/test_isolate.dart

  Future<void> _handle(int _m) async {
    final response = ReceivePort();
    isolateTest = await Isolate.spawn(_isolate, response.sendPort);
    final sendPort = await response.first as SendPort;
    final answer = ReceivePort();
    sendPort.send([_m, answer.sendPort]);
    await answer.first.then((p) { 
      _outbound.sink.add(p);});
  }

  static void _isolate(SendPort _initialReplyTo) {
    final port =  ReceivePort();
    _initialReplyTo.send(port.sendPort);
    port.listen((message) {
      final data = message[0] as int;
      final send = message[1] as SendPort;
      send.send(_syncHandle(data));
    });
  }
}

Future<String> _syncHandle(int data) async {
  return 'done';
}

note the send.send(_syncHandle(data)); part

if you do so, you can send only primitives and not futures,
basically that’s it

Answered By – Francesco Iapicca

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.