简体   繁体   中英

Flutter Isolate receives only the initial message

I'm trying to use an Isolate that will send a request, so as not to block the main thread/isolate.

After using so, the function of the spawned Isolate is called only once, on the initial passed message.

final isolate = await Isolate.spawn<Animal>((animal) {
  print('received ${animal.name}');
}, Animal("Foo"));

Prints: flutter: received Foo

But adding a few more shows nothing:

print('Sending bar');
isolate.controlPort.send(Animal("Bar"));

print('Sending test');
isolate.controlPort.send(Animal("Test"));

sleep(const Duration(seconds: 10));
flutter: Sending bar
flutter: Sending test
flutter: received Foo

After reading the docs of Isolate::spawn() , I achieved this by sending a SendPort to the Isolate whose handler sends its own SendPort for the main isolate to finally be able to send messages.

In action:

import 'dart:io';
import 'dart:isolate';

void main() async {
  final recvPort = ReceivePort();

  await Isolate.spawn<SendPort>((port) {
    print('[2] received port');

    final recvMsg = ReceivePort();

    port.send(recvMsg.sendPort);

    print('[2] sent my port');

    recvMsg.listen((message) {
      print('[2] Received ${message.name}');
    });
  }, recvPort.sendPort);

  final sendPort = await recvPort.first;

  print('[1] Sending bar');
  sendPort.send(Animal("Bar"));

  print('[1] Sending test');
  sendPort.send(Animal("Test"));

  sleep(const Duration(seconds: 5));

  exit(0);
}

class Animal {
  final String name;

  Animal(this.name);
}

Results in:

Results in:
[2] received port
[2] sent my port
[1] Sending bar
[1] Sending test
[2] Received Bar
[2] Received Test
Process finished with exit code 0

As detailed in the docs, this is actually meant for bidirectional communication between the isolates, but it's the only way I got working in my use case (unidirectional).

For bidirectional communication, I've created a gist that simply transforms the recvPort into a broadcast stream to first receive the isolate's SendPort , before receiving the actual messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM