perform<T> static method

Cmd perform<T>(
  1. Future<T> task(), {
  2. required Msg onSuccess(
    1. T result
    ),
  3. Msg onError(
    1. Object error,
    2. StackTrace stack
    )?,
})

A command that runs an async function and maps the result to a message.

This is a convenience for wrapping arbitrary async work.

Cmd.perform(
  () => httpClient.get(url),
  onSuccess: (response) => DataMsg(response.body),
  onError: (error) => ErrorMsg(error.toString()),
);

Implementation

static Cmd perform<T>(
  Future<T> Function() task, {
  required Msg Function(T result) onSuccess,
  Msg Function(Object error, StackTrace stack)? onError,
}) {
  return Cmd(() async {
    try {
      final result = await task();
      return onSuccess(result);
    } catch (e, stack) {
      if (onError != null) {
        return onError(e, stack);
      }
      rethrow;
    }
  });
}