ofArgFunc<Msg, Result, Arg> static method

Cmd<Msg> ofArgFunc<Msg, Result, Arg>(
  1. FutureOr<Result?> task(
    1. Arg
    ),
  2. Arg arg, {
  3. Msg onSuccess(
    1. Result
    )?,
  4. Msg? onMissing,
  5. Msg onThrow(
    1. dynamic
    )?,
})

Call a function that after returning a result, can be used to create and dispatch a new message.

task: Function that takes an input and returns a result that might be turned into a message. arg: Argument to be used when calling the function. onSuccess: Function that returns a message when the function terminated successfully using the returned non-null result from the task. onMissing: Message used when the function terminated successfully and returned a null value. onThrow: Function that returns a message when the function throws anything — covers both Exception and Error subclasses as well as any other thrown object.

Implementation

static Cmd<Msg> ofArgFunc<Msg, Result, Arg>(
    FutureOr<Result?> Function(Arg) task, Arg arg,
    {Msg Function(Result)? onSuccess,
    Msg? onMissing,
    Msg Function(dynamic)? onThrow}) {
  void bind(Dispatch<Msg> dispatch) async {
    try {
      final result = await task(arg);
      if (result != null) {
        if (onSuccess != null) {
          dispatch(onSuccess(result));
        }
      } else {
        if (onMissing != null) {
          dispatch(onMissing);
        }
      }
    } catch (e) {
      if (onThrow != null) {
        dispatch(onThrow(e));
      }
    }
  }

  return Cmd([bind]);
}