useStream<T> function

Ref<T?> useStream<T>(
  1. Stream<T> stream
)

Subscribes to a Stream and returns a Ref that is updated with the latest value from the stream.

The returned Ref will have a null value until the stream emits its first value.

Example:

final counterStream = Stream.periodic(Duration(seconds: 1), (i) => i);
final counter = useStream(counterStream);

// In your widget:
Text('${counter.value}'); // Will update every second

Implementation

Ref<T?> useStream<T>(Stream<T> stream) {
  final ret = ref<T?>(null);

  stream.listen((value) {
    ret.value = value;
  });

  return ret;
}