How to get a reference to an already running isolate?

Issue

How do you get a reference to an already running isolate during the start of a Flutter app?

Imagine a Futter app that performs all of its work in an Isolate. The Isolate can run for close to an hour even if the app is put into background (which btw. is working fine so far). The problem arises if the app is started again while the isolate is already running, in which cause the app hangs.

So the question is, how do you detect if the isolate is already running, and how can you get a handle to it?

Solution

Since my comments get no reply from the asker, I provide a more detailed proposal here. Feel free to comment and I will update based on the feedback.

Firstly, try to simply follow the tutorial: https://medium.com/flutter/executing-dart-in-the-background-with-flutter-plugins-and-geofencing-2b3e40a1a124

Secondly, the IsolateNameServer seems promising. Looking at its implementation, we see:

class IsolateNameServer {

...
  static SendPort? lookupPortByName(String name) {
...
    return _lookupPortByName(name);
  }

...

  static SendPort? _lookupPortByName(String name)
      native 'IsolateNameServerNatives_LookupPortByName';
  static bool _registerPortWithName(SendPort port, String name)
      native 'IsolateNameServerNatives_RegisterPortWithName';
  static bool _removePortNameMapping(String name)
      native 'IsolateNameServerNatives_RemovePortNameMapping'
}

and the c++ code: https://blog.weghos.com/flutter/engine/flutter/lib/ui/isolate_name_server/isolate_name_server_natives.cc.html

...
Dart_Handle IsolateNameServerNatives::LookupPortByName(
    const std::string& name) {
  auto name_server = UIDartState::Current()->GetIsolateNameServer();
  if (!name_server) {
    return Dart_Null();
  }
  Dart_Port port = name_server->LookupIsolatePortByName(name);
  if (port == ILLEGAL_PORT) {
    return Dart_Null();
  }
  return Dart_NewSendPort(port);
}
...

Therefore, it is not implemented in Dart, but implemented natively, so probably the background isolate can register itself and the main isolate can use this to find it.

Try it and if it does not work, please comment and I will update.

Answered By – ch271828n

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.