stream property

Stream<T> get stream

Converts this reactive value to a broadcast stream.

The stream emits the current value whenever the reactive value changes. Multiple listeners can subscribe to the same stream. The stream is automatically managed and cleaned up when the reactive value is disposed.

Returns: A broadcast stream that emits values when this reactive value changes

Example:

final counter = Signal(0);
final stream = counter.stream;

stream.listen((value) => print('Counter: $value'));
// Prints: "Counter: 0"
counter.value = 1; // Prints: "Counter: 1"
counter.value = 2; // Prints: "Counter: 2"

Implementation

Stream<T> get stream {
  assert(!isDisposed);
  var s = streamHolders[this] as StreamHolder<T>?;
  if (s == null) {
    streamHolders[this] = s = StreamHolder<T>(
      onListen: () {
        s!.setWatcher(untracked(() => Watcher(
              () => value,
              (newValue, __) {
                s!.sink.add(newValue);
              },
              when: this is IMutableCollection ? (_, __) => true : null,
            )));
      },
      onCancel: () {
        s?.clearWatcher();
      },
    );

    attachToJoltAttachments(this, s.dispose);
  }

  return s.stream;
}