voicemeeter-api-python/voicemeeterlib/subject.py

73 lines
2.2 KiB
Python
Raw Normal View History

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