mediatr 0.1.0 copy "mediatr: ^0.1.0" to clipboard
mediatr: ^0.1.0 copied to clipboard

outdated

Dart mediatr package. Central mediator that allows sending requests, and publishing events.

Dart mediator package #

Pure dart package. No dependencies in flutter can be run both in flutter and dart API's.

Inspired by https://github.com/jbogard/MediatR

Create and send a request #

 /// Create the request 
 class AddRequest extends IRequest<int> {
  final int i;

  AddRequest(this.i);
}

/// Create a request handler 
class AddRequestHandler extends IRequestHandler<int, AddRequest> {
  @override
  Future<int> call(AddRequest request) async {
    return request.i + 1;
  }
}
/// Register the handler to the mediator instance ( commonly stored as a singleton )
 final mediator = Mediator(Pipeline());

 mediator.registerHandler<int, AddRequest, AddRequestHandler>(
          () => AddRequestHandler(),
        );

/// Send the request througt the mediator instance
final addedOrFailure = await mediator.send<int, AddRequest>(
          AddRequest(2),
        );
print(addedOrFailure.fold((left) {
// an instance of Failure
},
(right) {
// The added number
}));

Adding a custom exception handler #


MyFailure? _errorHandler(Exception e) {
 if (e is CustomException) {
   return MyFailure('message');
 }
}

final mediator = Mediator(
 Pipeline(),
 errorHandler: _errorHandler,
);

class CustomException implements Exception {}

class MyFailure extends Failure {
 MyFailure(super.message);
}

Publishing events #

/// create an event extending IDomainEvent
class MyEvent extends IDomainEvent {
  @override
  String get name => 'MyEvent';
}

mediator.publish<MyEvent>(MyEvent());

Subscribe on events with functions #

/// subscribe on mediator instance
var unsubscribeFunc = mediator.subscribeWithFunc<MyEvent>((event){
 print(event.name);
});

/// call the func returned to unsubscribe
unsubscribeFunc();

Subscribe on events with a class instance #

class MyEventHandler extends IEventHandler<MyEvent> {
  @override
  Future<void> call(MyEvent event) {
    print(event);
  }
}
var eventHandler = MyEventHandler();

mediator.subscribe<MyEvent>(eventHandler);


/// call unsubscribe with the same instance to remove the handler.
mediator.unsubscribe<MyEvent>(eventHandler);

Adding a middleware for all requests #

class LoggingBehaviour extends IPipelineBehaviour {
  @override
  Future proccess(IRequest request, RequestHandlerDelegate next) {
    print(request);
    return next(request);
  }
}

final mediator = Mediator(
  Pipeline()
    ..addMiddleware(
      LoggingBehaviour(),
    ),
);
7
likes
0
points
330
downloads

Publisher

unverified uploader

Weekly Downloads

Dart mediatr package. Central mediator that allows sending requests, and publishing events.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

either_dart

More

Packages that depend on mediatr