ofFunc<Result, Model> static method

Cmd<Model> ofFunc<Result, Model>(
  1. FutureOr<Result> func(), {
  2. Update<Model> onSuccessUpdate(
    1. Model model,
    2. Result r
    )?,
  3. Model onSuccessModel(
    1. Model model,
    2. Result r
    )?,
  4. Cmd<Model> onSuccessCommands(
    1. Result r
    )?,
  5. Update<Model> onErrorUpdate(
    1. Model model,
    2. Exception e
    )?,
  6. Model onErrorModel(
    1. Model model,
    2. Exception e
    )?,
  7. Cmd<Model> onErrorCommands(
    1. Exception e
    )?,
  8. bool doRebuild = true,
})

Perform a function. Takes a mapping function to map the result to a Msg. Optionally takes a function to dispatch a message on Exception.

Implementation

static Cmd<Model> ofFunc<Result, Model>(
  FutureOr<Result> func(), {
  Update<Model> onSuccessUpdate(Model model, Result r)?,
  Model onSuccessModel(Model model, Result r)?,
  Cmd<Model> onSuccessCommands(Result r)?,
  Update<Model> onErrorUpdate(Model model, Exception e)?,
  Model onErrorModel(Model model, Exception e)?,
  Cmd<Model> onErrorCommands(Exception e)?,
  bool doRebuild = true,
}) =>
    Cmd.ofSub((dispatch) async {
      try {
        final result = await func();
        if (onSuccessUpdate != null) {
          dispatch((model) => onSuccessUpdate(model, result));
        } else if (onSuccessModel != null) {
          dispatch(fromModelMsg((model) => onSuccessModel(model, result),
              doRebuild: doRebuild));
        } else if (onSuccessCommands != null) {
          dispatch((model) => Update(model,
              commands: onSuccessCommands(result), doRebuild: doRebuild));
        }
      } on Exception catch (e) {
        if (onErrorUpdate != null) {
          dispatch((model) => onErrorUpdate(model, e));
        } else if (onErrorModel != null) {
          dispatch(fromModelMsg((model) => onErrorModel(model, e),
              doRebuild: doRebuild));
        } else if (onErrorCommands != null) {
          dispatch((model) => Update(model,
              commands: onErrorCommands(e), doRebuild: doRebuild));
        }
      }
    });