onValueChanges<R> method

StreamSubscription onValueChanges<R>(
  1. {Duration debounceTime = const Duration(),
  2. void onStart(
    1. State previous,
    2. State current
    )?,
  3. required Stream<R> onData(
    1. State previous,
    2. State current
    ),
  4. void onFinish(
    1. State previous,
    2. State current,
    3. R result
    )?}
)

Returns a StreamSubscription<R>,

onData is called with the state every time the values changes, after debounceTime.

onStart is called without debounceTime and before onData every time the values changes.

onFinish listen onData with a switchMap, therefore it will only receive elements of the last change.

Implementation

StreamSubscription<dynamic> onValueChanges<R>({
  Duration debounceTime = const Duration(),
  void Function(State previous, State current)? onStart,
  required Stream<R> Function(State previous, State current) onData,
  void Function(State previous, State current, R result)? onFinish,
}) {
  final _onStart = onStart ?? (_, __) {};

  final _onFinish = onFinish ?? (State p, State c, R r) {};

  return stream
      .startWith(state)
      .distinct((p, c) => p.value == c.value)
      .pairwise()
      .doOnData((states) => _onStart(states.first, states.last))
      .debounceTime(debounceTime)
      .switchMap<List<dynamic>>(
        (states) => onData(states.first, states.last)
            .map((r) => <dynamic>[states.first, states.last, r]),
      )
      .listen((list) =>
          _onFinish(list[0] as State, list[1] as State, list[2] as R));
}