The code for Flutter runs on the root isolate by default and is responsible for rendering and UI interaction. Usage scenario: Time-consuming tasks, such as reading and writing files and intensive computing, need to create an ISOLATE to process Web workers that look similar to JS

How do you create an ISOLATE?

Take a look at the schematic. There are 4 steps to do this:

  1. The first and second steps are a process of establishing a handshake
  2. The third and fourth steps are the process of sending the data and processing it and returning it

Concrete example code

Before you look at the code, take a look at a few key classes:

  1. SendPort is the only communication between the ISOLATE and any message can be sent.
  2. ReceivePort is a non-broadcast stream. Only one listener can receive a message

Corresponding test code:

  loadData() async {
    Create an Isolate using spawn, bind static methods and pass App port1
    print('spawn1');
    ReceivePort receivePort = ReceivePort();// Listen on App side
    await Isolate.spawn(dataLoader, receivePort.sendPort`);//spawn(port1)
    print('spawn2');

    // Obtain port2 on the new Isolate
    SendPort sendPort = await receivePort.first;
    print('spawn3');
    // pass the tasks to the port2 on the Isolate
    List dataList = await sendReceive(sendPort, 'https://jsonplaceholder.typicode.com/posts');// Encapsulate the specific task to be done as a Future method
    print('spawn4');
    print('dataList $dataList');
  }

  // Isolate processing method
  static dataLoader(SendPort sendPort) async {
    // Create a listening port2 and send a message to port2 on the Isolate through port1 on the APP
    ReceivePort receivePort = ReceivePort();// Monitor on Isolate
    print('Loader1');
    sendPort.send(receivePort.sendPort);// port1.send(port2);
    print('Loader2');
    // Monitor all messages sent by the App end and process them. You can pass keys, parameters, distinguish processing, etc
    await for (var msg in receivePort) {
      String requestURL = msg[0];
      SendPort callbackPort = msg[1];// port3
      print(requestURL);
      print('Loader3');

     /// assume processing tasks
      final dataList = await Future.delayed(Duration(seconds: 5), () {
        return ['sdf'.'ggg'];
      });
      print('Loader4');
      // The callback returns the value to the caller
      callbackPort.send(dataList);
      print('Loader5'); }}/// Create your own listening port and send messages to the new ISOLATE
  ///
  /// why create port3?
  ///
  ReceivePort is a Stream and can be monitored only once. In order to better isolate task monitoring, we create a ReceivePort.
  /// Try to write a listener for each task without affecting each other
  Future sendReceive(SendPort sendPort, String url) {
    // Task listener
    ReceivePort receivePort = ReceivePort();
    print('send1');
    // Send things to do
    sendPort.send([url, receivePort.sendPort]);//port2.send(tohandletask, port3);
    print('send2');
    // The return value is received and returned to the caller
    return receivePort.first;
  }
Copy the code

The log corresponding to the above code is as follows:

flutter: spawn1
flutter: Loader1
flutter: Loader2
flutter: spawn2
flutter: spawn3
flutter: send1
flutter: send2
flutter: https: / /jsonplaceholder.typicode.com/posts
flutter: Loader3
flutter: Loader4
flutter: Loader5
flutter: spawn4
flutter: dataList [sdf.ggg]
Copy the code

If you have any questions, please point out