2022-09-28 18:13:07 +01:00
|
|
|
import logging
|
|
|
|
|
2023-06-25 03:41:10 +01:00
|
|
|
logger = logging.getLogger(__name__)
|
2022-09-28 18:13:07 +01:00
|
|
|
|
|
|
|
|
2023-06-25 03:41:10 +01:00
|
|
|
class Subject:
|
2022-06-16 16:10:06 +01:00
|
|
|
def __init__(self):
|
2023-06-25 03:41:10 +01:00
|
|
|
"""Adds support for observers and callbacks"""
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
self._observers = list()
|
2023-06-25 03:41:10 +01:00
|
|
|
self.logger = logger.getChild(self.__class__.__name__)
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def observers(self) -> list:
|
|
|
|
"""returns the current observers"""
|
|
|
|
|
|
|
|
return self._observers
|
|
|
|
|
2023-06-25 03:41:10 +01:00
|
|
|
def notify(self, event):
|
2022-06-16 16:10:06 +01:00
|
|
|
"""run callbacks on update"""
|
|
|
|
|
2023-06-25 03:41:10 +01:00
|
|
|
for o in self._observers:
|
|
|
|
if hasattr(o, "on_update"):
|
|
|
|
o.on_update(event)
|
|
|
|
else:
|
|
|
|
if o.__name__ == f"on_{event}":
|
|
|
|
o()
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
def add(self, observer):
|
2023-06-25 03:41:10 +01:00
|
|
|
"""adds an observer to observers"""
|
2022-06-16 16:10:06 +01:00
|
|
|
|
2023-06-25 03:41:10 +01:00
|
|
|
try:
|
|
|
|
iterator = iter(observer)
|
|
|
|
for o in iterator:
|
|
|
|
if o not in self._observers:
|
|
|
|
self._observers.append(o)
|
|
|
|
self.logger.info(f"{o} added to event observers")
|
|
|
|
else:
|
|
|
|
self.logger.error(f"Failed to add {o} to event observers")
|
|
|
|
except TypeError:
|
|
|
|
if observer not in self._observers:
|
|
|
|
self._observers.append(observer)
|
|
|
|
self.logger.info(f"{observer} added to event observers")
|
|
|
|
else:
|
|
|
|
self.logger.error(f"Failed to add {observer} to event observers")
|
2022-09-28 18:13:07 +01:00
|
|
|
|
|
|
|
register = add
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
def remove(self, observer):
|
2023-06-25 03:41:10 +01:00
|
|
|
"""removes an observer from observers"""
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
try:
|
2023-06-25 03:41:10 +01:00
|
|
|
iterator = iter(observer)
|
|
|
|
for o in iterator:
|
|
|
|
try:
|
|
|
|
self._observers.remove(o)
|
|
|
|
self.logger.info(f"{o} removed from event observers")
|
|
|
|
except ValueError:
|
|
|
|
self.logger.error(f"Failed to remove {o} from event observers")
|
|
|
|
except TypeError:
|
|
|
|
try:
|
|
|
|
self._observers.remove(observer)
|
|
|
|
self.logger.info(f"{observer} removed from event observers")
|
|
|
|
except ValueError:
|
|
|
|
self.logger.error(f"Failed to remove {observer} from event observers")
|
2022-09-28 18:13:07 +01:00
|
|
|
|
|
|
|
deregister = remove
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
def clear(self):
|
2023-06-25 03:41:10 +01:00
|
|
|
"""clears the observers list"""
|
2022-06-16 16:10:06 +01:00
|
|
|
|
|
|
|
self._observers.clear()
|