flutter实践:Isolate应用实例二

需求:尝试将Isolate封装一层便于直接使用

实现:

1.定义一个封装类

class TdxIsolate {
  //创建一个isolate
  Isolate? newIsolate;
  //新isolate发送器
  SendPort? childSender;
  //存放结果集
  List results = [];

  //构造方法
  TdxIsolate() {
    //初始化isolate 
    createIsolate();
  }

  void dispose() {
    //界面销毁时一定要释放资源
    newIsolate?.kill(priority: Isolate.immediate);
  }
}

2.消息传递

在 Dart 中,Isolate 之间的消息传递是通过 SendPort 和 ReceivePort 来实现的。

SendPort 和 ReceivePort 是 Dart 中进行进程间通信的工具。

你可以通过 SendPort 发送消息,然后在对应的 ReceivePort 中接收消息。

当你创建一个 ReceivePort 时,它将自动生成一个与之关联的 SendPort。

// 初始化,创建isolate
  Future createIsolate() async {
    //主Isolate的ReceiverPort
    ReceivePort mainReceive = ReceivePort();
    newIsolate =
        await Isolate.spawn(childSearch, mainReceive.sendPort);//主Receive的sendPort传到新Isolate
    //返回的第一个消息
    childSender = await mainReceive.first;
    //关闭
    mainReceive.close();
  }
// 新Isolate的方法,负责处理数据解析
  static childSearch(SendPort mainSendPort) {
    //新Isolate的ReceivePort
    ReceivePort childReceivePort = ReceivePort();
    //新Isolate的sendPort传回主Isolate
    mainSendPort.send(childReceivePort.sendPort);
    // 监听子Isolate的传送装置,等待主isolate叫子Isolate处理数据
    childReceivePort.listen((package) async {
      MessagePackage _msg = package as MessagePackage;
      var sStr = _msg.msg["keys"];
      var aData = _msg.msg["data"];
      _msg.sender.send(getSearchResults(sStr, aData));
    });
  }
//耗时操作,遍历数据
static List getSearchResults(String searchStr, List data) {
    if (searchStr.isEmpty) {
      return [];
    }
    List>> results = [];
    for (var i = 0; i < data.length; i++) {
      var item = data[i];
      if (item is Map) {
        List> rowList = [];
        var j = 0;
        for (var key in item.keys) {
          var temp = item[key] is String ? item[key] : item[key].toString();
          if (temp.contains(searchStr)) {
            Map row = {};
            row[i] = j;
            rowList.add(row);
          }
          j++;
        }
        if (rowList.isNotEmpty) {
          results.add(rowList);
        }
      }
    }
    return results;
  }
}

3.定义一个Message

class MessagePackage {
  SendPort sender; // 临时发送器
  dynamic msg; // 消息
  MessagePackage(this.sender, this.msg);
}

4.开启isolate处理

isolateSearch(String searchStr, List allData) async {
    results.clear();
    if (searchStr.isEmpty) {
      return;
    }
    var data = {"keys": searchStr, "data": allData};
    ReceivePort _temp = ReceivePort();
    //新Isolate的sendPort发送消息给listen监听
    childSender!.send(MessagePackage(_temp.sendPort, data));
    //监听里处理完后返回数据到_temp
    await _temp.first.then((value) {
      results = value;
    });
    _temp.close();
  }

你可能感兴趣的:(flutter)