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

橙三吉。 提交于 2019-12-07 17:53:56

问题


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 ]


回答1:


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



来源:https://stackoverflow.com/questions/55571179/dart-flutter-async-behaviour-of-an-isolates-top-level-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!