useStreamSubscription<T> function

  1. @defineHook
StreamSubscription<T> useStreamSubscription<T>(
  1. Stream<T> stream,
  2. void onData(
    1. T event
    )?, {
  3. Function? onError,
  4. void onDone()?,
  5. bool? cancelOnError,
})

Subscribes to a Stream and automatically cancels the subscription when the widget is unmounted.

Parameters:

  • stream: The Stream to subscribe to
  • onData: Optional callback called when data is emitted
  • onError: Optional callback called when an error occurs
  • onDone: Optional callback called when the stream completes
  • cancelOnError: Whether to cancel the subscription on error (default: false)

Example:

final controller = StreamController<int>();
useStreamSubscription(
  controller.stream,
  onData: (value) {
    print('Received: $value');
  },
  onError: (error, stackTrace) {
    print('Error: $error');
  },
  onDone: () {
    print('Stream completed');
  },
);
controller.add(42);

Implementation

@defineHook
StreamSubscription<T> useStreamSubscription<T>(
  Stream<T> stream,
  void Function(T event)? onData, {
  Function? onError,
  void Function()? onDone,
  bool? cancelOnError,
}) {
  return useHook(_UseStreamSubscriptionHook(
      stream, onData, onError, onDone, cancelOnError));
}