2022-08-13 03:54:16 +00:00
|
|
|
# Python imports
|
2022-09-29 22:22:33 +00:00
|
|
|
from collections import defaultdict
|
2022-08-13 03:54:16 +00:00
|
|
|
|
|
|
|
# Lib imports
|
|
|
|
|
|
|
|
# Application imports
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class EventSystem:
|
2022-09-29 22:22:33 +00:00
|
|
|
""" Create event system. """
|
2022-08-13 03:54:16 +00:00
|
|
|
|
|
|
|
def __init__(self):
|
2022-09-29 22:22:33 +00:00
|
|
|
self.subscribers = defaultdict(list)
|
|
|
|
|
|
|
|
|
|
|
|
def subscribe(self, event_type, fn):
|
|
|
|
self.subscribers[event_type].append(fn)
|
|
|
|
|
2022-10-01 04:30:38 +00:00
|
|
|
def emit(self, event_type, data = None):
|
2022-09-29 22:22:33 +00:00
|
|
|
if event_type in self.subscribers:
|
|
|
|
for fn in self.subscribers[event_type]:
|
|
|
|
if data:
|
2022-09-29 22:32:35 +00:00
|
|
|
if hasattr(data, '__iter__') and not type(data) is str:
|
2022-09-29 22:22:33 +00:00
|
|
|
fn(*data)
|
|
|
|
else:
|
|
|
|
fn(data)
|
|
|
|
else:
|
|
|
|
fn()
|
2022-12-04 00:22:20 +00:00
|
|
|
|
|
|
|
# NOTE: Should be used when signal has only one listener and vis-a-vis
|
|
|
|
def emit_and_await(self, event_type, data = None):
|
|
|
|
if event_type in self.subscribers:
|
|
|
|
for fn in self.subscribers[event_type]:
|
|
|
|
if data:
|
|
|
|
if hasattr(data, '__iter__') and not type(data) is str:
|
|
|
|
return fn(*data)
|
|
|
|
else:
|
|
|
|
return fn(data)
|
|
|
|
else:
|
|
|
|
return fn()
|