2022-09-29 11:31:19 +01:00
|
|
|
import logging
|
|
|
|
|
|
|
|
|
2022-06-16 14:07:12 +01:00
|
|
|
class Subject:
|
|
|
|
"""Adds support for observers"""
|
|
|
|
|
2022-09-29 11:31:19 +01:00
|
|
|
logger = logging.getLogger("subject.subject")
|
|
|
|
|
2022-06-16 14:07:12 +01:00
|
|
|
def __init__(self):
|
|
|
|
"""list of current observers"""
|
|
|
|
|
|
|
|
self._observers = list()
|
|
|
|
|
|
|
|
@property
|
|
|
|
def observers(self) -> list:
|
|
|
|
"""returns the current observers"""
|
|
|
|
|
|
|
|
return self._observers
|
|
|
|
|
2022-07-24 14:38:16 +01:00
|
|
|
def notify(self, modifier):
|
2022-06-16 14:07:12 +01:00
|
|
|
"""run callbacks on update"""
|
|
|
|
|
2022-06-20 00:06:03 +01:00
|
|
|
[o.on_update(modifier) for o in self._observers]
|
2022-06-16 14:07:12 +01:00
|
|
|
|
|
|
|
def add(self, observer):
|
|
|
|
"""adds an observer to _observers"""
|
|
|
|
|
|
|
|
if observer not in self._observers:
|
|
|
|
self._observers.append(observer)
|
2022-09-29 11:31:19 +01:00
|
|
|
self.logger.info(f"{type(observer).__name__} added to event observers")
|
2022-06-16 14:07:12 +01:00
|
|
|
else:
|
2022-09-29 11:31:19 +01:00
|
|
|
self.logger.error(
|
|
|
|
f"Failed to add {type(observer).__name__} to event observers"
|
|
|
|
)
|
2022-06-16 14:07:12 +01:00
|
|
|
|
|
|
|
def remove(self, observer):
|
|
|
|
"""removes an observer from _observers"""
|
|
|
|
|
|
|
|
try:
|
|
|
|
self._observers.remove(observer)
|
2022-09-29 11:31:19 +01:00
|
|
|
self.logger.info(f"{type(observer).__name__} removed from event observers")
|
2022-06-16 14:07:12 +01:00
|
|
|
except ValueError:
|
2022-09-29 11:31:19 +01:00
|
|
|
self.logger.error(
|
|
|
|
f"Failed to remove {type(observer).__name__} from event observers"
|
|
|
|
)
|
2022-06-16 14:07:12 +01:00
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
"""clears the _observers list"""
|
|
|
|
|
|
|
|
self._observers.clear()
|