initialize method

Future<void> initialize()

Initializes the isolate and sets up communication

Implementation

Future<void> initialize() async {
  if (_isInitialized) return;

  _receivePort = ReceivePort();

  // Spawn the isolate
  _isolate = await Isolate.spawn(
    _isolateEntryPoint<T, R>,
    _IsolateSetup(
      sendPort: _receivePort!.sendPort
    ),
  );

  // Listen for messages from the isolate
  final completer = Completer<void>();

  _receivePort!.listen((message) {
    if (message is SendPort) {
      // Initial handshake - receive the isolate's SendPort
      _isolateSendPort = message;
      _isInitialized = true;
      completer.complete();
    } else if (message is _JobResult<R>) {
      // Handle job results
      final completer = _jobCompleterMap.remove(message.jobId);
      if (message.error != null) {
        completer?.completeError(message.error!, message.stackTrace);
      } else {
        completer?.complete(message.result);
      }
    }
  });

  await completer.future;
}