injectStream<T> method
Injects stream on JS globalThis as an async iterable.
JavaScript consumes the values with for await (const value of name).
Each pull requests the next Dart event, preserving backpressure. Stream
errors reject the pending JS iteration and completion ends the iterator.
The injected iterable remains available until the runtime is rebuilt or
disposed; this method intentionally does not create a separate handle.
Implementation
Future<void> injectStream<T>(String name, Stream<T> stream) async {
final terminalError = _terminalError;
if (terminalError != null) {
return Future<void>.error(terminalError);
}
final validName = _validateGlobalName(name);
final callbackId = _nextCallbackId++;
final callbackName = '__jsInjectedStream_$callbackId';
await _bindRuntimeCallback(callbackId, callbackName, (_) async => stream);
try {
await evalRaw('''
(async () => {
globalThis[${jsonEncode(validName)}] = await globalThis[${jsonEncode(callbackName)}]();
})()
''', name: '<injectStream:$validName>');
} finally {
await _unbindRuntimeCallback(callbackId);
}
}