request<R> method
Send a typed request to Web Worker and await the response.
Creates a dedicated MessageChannel for the reply, sends the request, and waits for exactly one response. Perfect for offloading CPU-intensive work to Web Workers while maintaining type safety.
Parameters:
command: Command string for the workerdata: Optional data payloadtimeout: Maximum wait time (default: 3 seconds)
Usage: {@tool snippet example/web_example.dart} {@end-tool}
Implementation
Future<R> request<R>(
String command, {
Map<String, Object?>? data,
Duration timeout = const Duration(seconds: 3),
}) async {
final completer = Completer<Object?>();
final reply = MessageChannel();
reply.port2.onmessage = ((MessageEvent msg) {
if (completer.isCompleted) return;
completer.complete(msg.data?.dartify());
}).toJS;
sendCmd(
command,
data: {...?data, 'reply': reply.port1},
transfer: reply.port1,
);
try {
final obj = await completer.future.timeout(
timeout,
onTimeout: () {
throw TimeoutException(
'request("$command") timed out after $timeout',
);
},
);
if (obj is Map && obj['error'] != null) {
throw StateError('request("$command") failed: ${obj['error']}');
}
try {
return obj as R;
} on TypeError {
throw StateError(
'request("$command") returned incompatible type: ${obj.runtimeType} expected: $R',
);
}
} finally {
reply.port1.close();
reply.port2.close();
}
}