select<T> method

Stream<T> select<T>(
  1. T selector(
    1. TState state
    )
)

Returns a stream that only emits when the selected value changes.

selector - Function that extracts the value to observe from state.

The stream will:

  • Emit immediately with the current selected value
  • Only emit subsequent values when they differ from the previous value
  • Use == for equality comparison

Example:

final countStream = bloc.select((state) => state.count);
countStream.listen((count) {
  // Only called when count actually changes
  print('New count: $count');
});

Implementation

Stream<T> select<T>(T Function(TState state) selector) {
  T? previous;
  bool isFirst = true;

  return stream.map((status) => selector(status.state)).where((value) {
    if (isFirst) {
      isFirst = false;
      previous = value;
      return true;
    }
    if (value == previous) return false;
    previous = value;
    return true;
  });
}