flutter isolate 主和子相互交流

library flutter_flutterisolate2;

import 'dart:async';
import 'dart:isolate';

///
/// Isolate 默认是主的, 在主Isolate中启动的子Isolate需要交互需要用到SendPort
main() async {
  ///沟通需要的接收port
  ReceivePort childReceiveMainPort = new ReceivePort();

  ///创建一个子Isolate,得到子Isolate的接收器和发送器
  await Isolate.spawn<SendPort>(_isolateChildFunction, childReceiveMainPort.sendPort);
  SendPort fromChildSendPort = await childReceiveMainPort.first;

  ReceivePort _chatReceivePort = ReceivePort();
  fromChildSendPort.send(["洞拐", _chatReceivePort.sendPort]);
  String receiveMessage = await _chatReceivePort.first;
  print('receiveMessage  $receiveMessage');
}

///需要交互的子函数
_isolateChildFunction(SendPort fromMainSendPort) async {
  ReceivePort childReceivePort = new ReceivePort();
  fromMainSendPort.send(childReceivePort.sendPort);

  dynamic _fromMainMessage = await childReceivePort.first;
  String _mainMessage = _fromMainMessage[0];
  SendPort _fromMainSendPort = _fromMainMessage[1];
  _fromMainSendPort.send("洞妖洞妖我是:" + _mainMessage);
}

image.png
library flutter_flutterisolate2;

import 'dart:async';
import 'dart:isolate';

///
/// Isolate 默认是主的, 在主Isolate中启动的子Isolate需要交互需要用到SendPort
main() async {
  ///沟通需要的接收port
  ReceivePort childReceiveMainPort = new ReceivePort();

  ///创建一个子Isolate,得到子Isolate的接收器和发送器
  await Isolate.spawn<SendPort>(_isolateChildFunction, childReceiveMainPort.sendPort);
  childReceiveMainPort.listen((message) {
    dynamic _msgObj = message;
    int _index = _msgObj[0];
    if (_index == 0) {
      SendPort fromChildSendPort = _msgObj[1];
      fromChildSendPort.send("洞拐");
    } else if (_index == 1) {
      print('receiveMessage  ${_msgObj[1]}');
    }
  });
}

///需要交互的子函数
_isolateChildFunction(SendPort fromMainSendPort) async {
  ReceivePort childReceivePort = new ReceivePort();
  fromMainSendPort.send([0, childReceivePort.sendPort]);

  dynamic _fromMainMessage = await childReceivePort.first;
  String _mainMessage = _fromMainMessage;
  fromMainSendPort.send([1, "洞妖洞妖我是:" + _mainMessage]);
}

不需要多次创建ReceivePort

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容