useStreamDefault<T> function

Ref<T> useStreamDefault<T>(
  1. Stream<T> stream, {
  2. required T defaultValue,
})

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

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

Example:

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

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

Implementation

Ref<T> useStreamDefault<T>(Stream<T> stream, {required T defaultValue}) {
  final ret = ref<T>(defaultValue);

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

  return ret;
}