setState method

  1. @override
Future<T?> setState(
  1. Object? mutator(
    1. T s
    ), {
  2. SideEffects<T>? sideEffects,
  3. StateInterceptor<T>? stateInterceptor,
  4. bool shouldOverrideDefaultSideEffects(
    1. SnapState<T> snap
    )?,
  5. int debounceDelay = 0,
  6. int throttleDelay = 0,
})
override

Mutate the state of the model and notify observers.

  • Required parameters:
  • The mutation function. It takes the current state fo the model. The function can have any type of return including Future and Stream.
  • Optional parameters:
  • sideEffects: Used to handle side effects resulting from calling this method. It takes SideEffects object. Notice that SideEffects.initState and SideEffects.dispose are never called here.
  • shouldOverrideDefaultSideEffects: used to decide when to override the default side effects defined in RM.inject and other equivalent methods.
  • debounceDelay: time in milliseconds to debounce the execution of setState.
  • throttleDelay: time in milliseconds to throttle the execution of setState.

Implementation

@override
Future<T?> setState(
  Object? Function(T s) mutator, {
  SideEffects<T>? sideEffects,
  StateInterceptor<T>? stateInterceptor,
  bool Function(SnapState<T> snap)? shouldOverrideDefaultSideEffects,
  int debounceDelay = 0,
  int throttleDelay = 0,
}) {
  initialize();
  final stackTrace = kDebugMode ? StackTrace.current : null;
  Future<T?> call() {
    final r = setStateNullable(
      (s) {
        return mutator(_snapState.state);
      },
      middleSetState: (status, result) => middleSetState(
        status,
        result,
        sideEffects: sideEffects,
        stateInterceptor: stateInterceptor,
        shouldOverrideDefaultSideEffects: shouldOverrideDefaultSideEffects,
      ),
      stackTrace: stackTrace,
    );
    if (r is T?) {
      return Future.value(r);
    }
    return r;
  }

  if (debounceDelay > 0) {
    _debounceTimer?.cancel();
    _debounceTimer = Timer(
      Duration(milliseconds: debounceDelay),
      () {
        call();
        _debounceTimer = null;
      },
    );
    return Future.value(_snapState.state);
  } else if (throttleDelay > 0) {
    if (_debounceTimer != null) {
      return Future.value(_snapState.state);
    }
    _debounceTimer = Timer(
      Duration(milliseconds: throttleDelay),
      () {
        _debounceTimer = null;
      },
    );
  }
  return call();
}