init method
Initializes the background Isolate.
Returns true if the Isolate spawned successfully.
Implementation
@override
Future<bool> init() async {
final receivePort = ReceivePort();
_receivePort = receivePort;
_exitCompleter = Completer<void>();
final completer = Completer<SendPort>();
receivePort.listen((message) {
if (message is _ReadyMessage) {
completer.complete(message.sendPort);
return;
}
if (message is _HandleIdNotification) {
_handleId = message.handleId;
return;
}
if (message is _Response) {
final pending = _pending.remove(message.id);
pending?.complete(message);
return;
}
// Isolate exit (null from addOnExitListener).
if (message == null) {
if (_exitCompleter != null && !_exitCompleter!.isCompleted) {
_exitCompleter!.complete();
}
if (!completer.isCompleted) {
completer.completeError(
StateError('Isolate exited before sending _ReadyMessage'),
);
}
_failAllPending('Isolate exited');
return;
}
// Isolate error (List from addErrorListener) — fail pending futures.
if (!completer.isCompleted) {
completer.completeError(
StateError('Isolate failed to start: $message'),
);
}
_failAllPending('Isolate error: $message');
});
final isolate = await Isolate.spawn(
_isolateEntryPoint,
_InitMessage(receivePort.sendPort),
);
_isolate = isolate;
isolate
..addOnExitListener(receivePort.sendPort)
..addErrorListener(receivePort.sendPort);
_sendPort = await completer.future.timeout(
initTimeout ?? const Duration(seconds: 30),
onTimeout: () => throw StateError(
'Worker isolate failed to initialize within timeout. '
'Possible silent crash before _ReadyMessage was sent.',
),
);
// Initialize FFI on the main isolate so that MontyCancelToken and
// direct NativeBindingsFfi access work cross-isolate. Dart static
// state is per-isolate, so the worker's NativeBindingsFfi registration
// does not propagate here.
NativeBindingsFfi.ensureInitialized();
return true;
}