/*
 * @author lsy
 * @date   2019-10-21
 **/

import 'dart:isolate';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';

class IsolateUtil {
  static ReceivePort receivePort = ReceivePort();

  static Future<T> paseJsonByIsolate<T>(Function function) async {
    // 通过spawn新建一个isolate,并绑定静态方法
    await Isolate.spawn(dataLoader, receivePort.sendPort);
    // 获取新isolate的监听port
    SendPort sendPort = await receivePort.first;
    // 调用sendReceive自定义方法
    return await sendReceive(sendPort, function);
  }

// isolate的绑定方法
  static dataLoader(SendPort sendPort) async {
    // 创建监听port,并将sendPort传给外界用来调用
    ReceivePort receivePort = ReceivePort();
    sendPort.send(receivePort.sendPort);

    // 监听外界调用
    await for (var msg in receivePort) {
      SendPort callbackPort = msg[0];
      Function function = msg[1];
      callbackPort.send(function());
    }
  }

// 创建自己的监听port,并且向新isolate发送消息
  static Future sendReceive(SendPort sendPort, Function function) {
    ReceivePort receivePort = ReceivePort();
    sendPort.send([receivePort.sendPort, function]);
    // 接收到返回值,返回给调用者
    return receivePort.first;
  }


}