konradhalas / buslane

Simple message (event/command) bus.
MIT License
31 stars 2 forks source link

Allow unregistering `EventHandler`s #3

Open ruancomelli opened 3 years ago

ruancomelli commented 3 years ago

First of all, thank you so much for this project!

I'd like to suggest an additional feature: unregistering EventHandlers.

Unregistering would work as follows:

from buslane import Event, EventBus, EventHandler

class MyEvent(Event):
    pass

class MyHandler(EventHandler[MyEvent]):
    def handle(self, event: MyEvent) -> None:
        print('Handling an event.')

bus = EventBus()

handler = MyHandler()

bus.register(handler)
bus.publish(MyEvent()) # prints "Handling an event."

bus.unregister(handler)
bus.publish(MyEvent()) # prints nothing

My motivation is that I am monitoring a system, and sometimes an automated agent is called to observe events and handle them. This agent was trivially implemented as an EventHandler. But, after some conditions are met, this agent becomes unnecessary and can be safely unregistered. In fact, since those agents are constantly created and registered, without unregistering unnecessary agents I ended up having millions of "dead" handlers. So unregistering seems natural at least in this application.

I already have this implemented and would be very glad to submit a PR if you agree that this is an interesting functionality.