listenValueChanges<R> method

StreamSubscription listenValueChanges<R>({
  1. Duration debounceTime = const Duration(),
  2. bool equals(
    1. T previous,
    2. T current
    )?,
  3. void onStart(
    1. T previous,
    2. T current
    )?,
  4. required Stream<R> onData(
    1. T previous,
    2. T current
    ),
  5. void onFinish(
    1. T previous,
    2. T current,
    3. R result
    )?,
  6. Function? onError,
  7. void onDone()?,
})

Allows you to provide a function that will be executed whenever a value changes. Listen for changes in the stream and call onStart. onData is called, with the previous value and the current value, after a debounceTime and only if the value has changed does it return a result which is passed to onFinish.

More over, it lets you provide a function equals to describe when to values can be considered the same

Implementation

/// Listen for changes in the stream and call [onStart].
/// [onData] is called, with the previous value and the current value, after a [debounceTime]
/// and only if the value has changed does it return a result which is passed to [onFinish].
///
/// More over, it lets you provide a function [equals] to describe when to values can be considered the same
StreamSubscription<dynamic> listenValueChanges<R>({
  Duration debounceTime = const Duration(),
  bool Function(T previous, T current)? equals,
  void Function(T previous, T current)? onStart,
  required Stream<R> Function(T previous, T current) onData,
  void Function(T previous, T current, R result)? onFinish,
  Function? onError,
  void Function()? onDone,
}) {
  final onStartFn = onStart ?? (T p, T c) {};
  final onFinishFn = onFinish ?? ((T p, T c, R r) => r);

  return distinct(equals)
      .pairwise()
      .doOnData((vls) => onStartFn(vls.first, vls.last))
      .debounceTime(debounceTime)
      .switchMap<List<dynamic>>((vls) {
    return onData(vls.first, vls.last).map((result) => <dynamic>[vls.first, vls.last, result]);
  }).listen(
    (list) => onFinishFn(list[0] as T, list[1] as T, list[2] as R),
    onError: onError,
    onDone: onDone,
  );
}