2022-08-12 22:54:16 -05:00
|
|
|
# Python imports
|
2022-09-29 17:22:33 -05:00
|
|
|
from collections import defaultdict
|
2022-08-12 22:54:16 -05:00
|
|
|
|
|
|
|
|
# Lib imports
|
|
|
|
|
|
|
|
|
|
# Application imports
|
2023-03-27 20:07:17 -05:00
|
|
|
from .singleton import Singleton
|
2022-08-12 22:54:16 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-03-27 20:07:17 -05:00
|
|
|
class EventSystem(Singleton):
|
2022-09-29 17:22:33 -05:00
|
|
|
""" Create event system. """
|
2022-08-12 22:54:16 -05:00
|
|
|
|
|
|
|
|
def __init__(self):
|
2022-09-29 17:22:33 -05:00
|
|
|
self.subscribers = defaultdict(list)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def subscribe(self, event_type, fn):
|
|
|
|
|
self.subscribers[event_type].append(fn)
|
|
|
|
|
|
2023-01-22 19:51:45 -06:00
|
|
|
def unsubscribe(self, event_type, fn):
|
|
|
|
|
self.subscribers[event_type].remove(fn)
|
|
|
|
|
|
|
|
|
|
def unsubscribe_all(self, event_type):
|
|
|
|
|
self.subscribers.pop(event_type, None)
|
|
|
|
|
|
2022-09-30 23:30:38 -05:00
|
|
|
def emit(self, event_type, data = None):
|
2022-09-29 17:22:33 -05:00
|
|
|
if event_type in self.subscribers:
|
|
|
|
|
for fn in self.subscribers[event_type]:
|
|
|
|
|
if data:
|
2022-09-29 17:32:35 -05:00
|
|
|
if hasattr(data, '__iter__') and not type(data) is str:
|
2022-09-29 17:22:33 -05:00
|
|
|
fn(*data)
|
|
|
|
|
else:
|
|
|
|
|
fn(data)
|
|
|
|
|
else:
|
|
|
|
|
fn()
|
2022-12-03 18:22:20 -06:00
|
|
|
|
|
|
|
|
def emit_and_await(self, event_type, data = None):
|
2023-01-22 19:51:45 -06:00
|
|
|
""" NOTE: Should be used when signal has only one listener and vis-a-vis """
|
2022-12-03 18:22:20 -06:00
|
|
|
if event_type in self.subscribers:
|
2023-03-05 15:42:11 -06:00
|
|
|
response = None
|
2022-12-03 18:22:20 -06:00
|
|
|
for fn in self.subscribers[event_type]:
|
|
|
|
|
if data:
|
|
|
|
|
if hasattr(data, '__iter__') and not type(data) is str:
|
2023-03-05 15:42:11 -06:00
|
|
|
response = fn(*data)
|
2022-12-03 18:22:20 -06:00
|
|
|
else:
|
2023-03-05 15:42:11 -06:00
|
|
|
response = fn(data)
|
2022-12-03 18:22:20 -06:00
|
|
|
else:
|
2023-03-05 15:42:11 -06:00
|
|
|
response = fn()
|
|
|
|
|
|
|
|
|
|
if not response in (None, ''):
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
return response
|