subscribeStream<T> method
Subscribes to a long-running native hardware stream or event channel.
Returns a broadcast Stream emitting typed data T from the host platform.
Example:
final locationStream = subscribeStream<Map<String, double>>('onLocationUpdate');
Implementation
Stream<T> subscribeStream<T>(String streamName, [Map<String, dynamic>? args]) {
if (!_streamControllers.containsKey(streamName)) {
final controller = StreamController<dynamic>.broadcast();
_streamControllers[streamName] = controller;
// Wire real native EventChannel if available
if (_eventChannel != null) {
try {
final nativeStream = _eventChannel!.receiveBroadcastStream({
'stream': streamName,
if (args != null) ...args,
});
final sub = nativeStream.listen(
(event) {
if (!controller.isClosed) {
controller.add(event);
}
},
onError: (err, stack) {
if (!controller.isClosed) {
if (err is PlatformException) {
controller.addError(_mapPlatformException(err, stack));
} else {
controller.addError(err, stack);
}
}
},
);
_nativeSubscriptions[streamName] = sub;
} catch (_) {
// Native channel unavailable (e.g. test harness / mock mode)
}
}
}
final controller = _streamControllers[streamName]!;
return controller.stream.cast<T>();
}