Komtet / mediator

A library implements the Mediator pattern to make your code extensible
MIT License
19 stars 3 forks source link

Getting listener return value from mediator itself #8

Open skynyrd opened 6 years ago

skynyrd commented 6 years ago

Hi, first I appreciate your simple and useful library.

I tried to use mediator in my Sanic app and I want to get the returned value from listener.

For example:

My listener:

def check_order_pattern_listener(event: CheckOrderPatternEvent):
    print(event.example_field)
    return 33333
@rule_route.route('/')
async def redirect_user(request):
    return_val = request.app.mediator.dispatch(CheckOrderPatternEvent("Hello World"))  #return_val is event here, but I want to get 33333?
    return json("Hello World")

I can fork the repo and return it from dispatch method but I wonder why you are returning event, and may be I am missing something here.

Thanks,

ghost commented 6 years ago

Hi, @skynyrd !

You can do something like this:

def listener(myevent):
    myevent.returnvalue = 33333

myevent = mediator.dispatch(MyEvent())
print(myevent.returnvalue)

return it from dispatch method

What if there are multiple listeners?

skynyrd commented 6 years ago

Hey @Kilte,

Indeed I could pass return value to the event itself as you suggested, but I think this time event is becoming kinda dto and single responsibility is broken.

And yes my suggestion works for command/command handler usage but fails for events (multiple listeners) Maybe list of a tuple of the result and the listener name can be returned ama it's a bit overkill.

Thinking about that :)

alexandertsema commented 4 years ago

@ghost @skynyrd event should not have a return value by definition, it is a fact that already happened in the system. Thus having a distinction between commands and events is necessary here. A command should have a return value imho.