3

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 ]

Francesco Iapicca
  • 2,618
  • 5
  • 40
  • 85

1 Answers1

0

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

Francesco Iapicca
  • 2,618
  • 5
  • 40
  • 85
  • Don't we need to create functions that we pass into the isolates as top level functions ?? Can we declare them inside, let's say a class ? I tried your code and It seems as everything is working even If I put it inside a class. What's the difference? – Divyam Dhadwal Jan 26 '23 at 21:17
  • maybe was true 4 years ago, I don't remember – Francesco Iapicca Jan 27 '23 at 10:51