command_bus 1.2.0 copy "command_bus: ^1.2.0" to clipboard
command_bus: ^1.2.0 copied to clipboard

Minimal command bus toolkit with middleware, safe result handling, and examples.

example/command_bus_example.dart

import 'package:command_bus/command_bus.dart';

Future<void> main() async {
  final bus = CommandBus<dynamic>(
    middlewares: [LoggingMiddleware()],
    state: null,
  );

  bus.register(GetLengthHandler());

  final length = await bus.dispatch(const GetLength('Hello, CommandBus!'));
  print('Length = $length'); // -> Length = 18

  final safeResult = await bus.dispatchSafe(const GetLength(''));
  if (safeResult.isSuccess) {
    print('Safe length = ${safeResult.data}');
  } else {
    print('Safe error: ${safeResult.error}');
    // -> Safe error: Invalid argument(s): String must not be empty
  }

  bus.unregister<GetLength>();
}

class GetLength extends Command<int> {
  final String value;

  const GetLength(this.value);
}

class GetLengthHandler extends CommandHandler<GetLength, int, dynamic> {
  @override
  int handle(GetLength command, dynamic state) {
    if (command.value.isEmpty) {
      throw ArgumentError('String must not be empty');
    }
    return command.value.length;
  }
}

class LoggingMiddleware extends CommandMiddleware {
  @override
  Future<R> handle<R>(Command<R> command, Next<R> next) async {
    print('Dispatching ${command.runtimeType}');
    // -> Dispatching GetLength
    final result = await next();
    print('Finished ${command.runtimeType}');
    // -> Finished GetLength
    return result;
  }
}
1
likes
155
points
199
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Minimal command bus toolkit with middleware, safe result handling, and examples.

Repository (GitHub)
View/report issues

License

MIT (license)

More

Packages that depend on command_bus