useBlocComparativeBuilder<C extends BlocBase, S> function

S useBlocComparativeBuilder<C extends BlocBase, S>(
  1. BlocBase<S> bloc, {
  2. required BlocComparativeBuilderCondition<S> buildWhen,
})

Returns current state of BlocBase class basing on state's comparison

The useBlocComparativeBuilder will filter any state, via specified buildWhen parameter.

For building bloc's state without condition, see useBlocBuilder.

buildWhen local filter function, that will filter incoming states from BlocBase.stream with access to the previous and current value.

Implementation

S useBlocComparativeBuilder<C extends BlocBase, S>(
  BlocBase<S> bloc, {
  required BlocComparativeBuilderCondition<S> buildWhen,
}) {
  // The stream doesn't support filtering with the previous and current value
  // We have to manually store previous value, especially for initial state
  final currentState = useRef(bloc.state);

  final state = useMemoized(
    () => bloc.stream.where(
      (nextState) {
        final shouldRebuild = buildWhen(currentState.value, nextState);
        currentState.value = nextState;
        return shouldRebuild;
      },
    ),
    [bloc],
  );

  return useStream(
    state,
    initialData: bloc.state,
    preserveState: false,
  ).requireData!;
}