diff --git a/structio/sync.py b/structio/sync.py index 4656346..2afbdd8 100644 --- a/structio/sync.py +++ b/structio/sync.py @@ -384,12 +384,28 @@ async def emit(evt: str, *args, **kwargs): def register_event(evt: str, func: Callable[[Any, Any], Coroutine[Any, Any, Any]]): """ - Register the given async function for the given event name + Register the given async function for the given event name. + Note that if the given async function is already registered + for the chosen event, it will be called once for each time + this function is called once the associated event is fired """ _events[evt].append(func) +def unregister_event(evt: str, func: Callable[[Any, Any], Coroutine[Any, Any, Any]]): + """ + Unregisters the given async function from the given event. + Nothing happens if the given event or async functions are + not registered yet + """ + + try: + _events[evt].remove(func) + except IndexError: + pass + + def on_event(evt: str): """ Convenience decorator to diff --git a/tests/smart_events.py b/tests/smart_events.py new file mode 100644 index 0000000..573ac59 --- /dev/null +++ b/tests/smart_events.py @@ -0,0 +1,17 @@ +import structio + + +@structio.on_event("on_message") +async def test(evt, *args, **kwargs): + print(f"[test] New event {evt!r} with arguments: {args}, {kwargs}") + # Simulate some work + await structio.sleep(1) + + +async def main(): + print(f"[main] Firing two events, exiting in two seconds") + await structio.emit("on_message", 1, 2, 3) + await structio.emit("on_message", 1, 2, 4) + + +structio.run(main)