initWorker method
Spawns the background isolate and completes the handshake.
spawnFn receives the SendPort to pass to the isolate entry point and
must return the spawned Isolate. The entry point must send its own
ReceivePort's SendPort back as the first message.
On failure, the isolate is killed and the receive port closed before rethrowing.
When markReady is true (the default), sets isReady to true after the
handshake. Pass false for two-phase initialization where a subsequent
operation must succeed before the worker is ready (use markInitialized
to set isReady when appropriate).
Implementation
Future<void> initWorker(
Future<Isolate> Function(SendPort sendPort) spawnFn, {
Duration timeout = const Duration(seconds: 30),
String timeoutMessage = 'Worker initialization timed out',
void Function(dynamic)? onResponse,
bool markReady = true,
}) async {
try {
rpc.isolate = await spawnFn(rpc.receivePort.sendPort);
rpc.sendPort = await setupIsolateHandshake(
receivePort: rpc.receivePort,
onResponse: onResponse ?? (msg) => rpc.handleResponse(msg),
timeout: timeout,
timeoutMessage: timeoutMessage,
);
if (markReady) _initialized = true;
} catch (e) {
rpc.isolate?.kill(priority: Isolate.immediate);
rpc.receivePort.close();
rethrow;
}
}