2018-03-07 09:12:58 +00:00
|
|
|
from functools import partial
|
|
|
|
|
2019-07-24 13:17:16 +00:00
|
|
|
from .lazy import lazy_property
|
2018-06-01 12:21:32 +00:00
|
|
|
|
2018-03-07 09:12:58 +00:00
|
|
|
|
|
|
|
class CallbackMixin:
|
2018-06-02 09:48:34 +00:00
|
|
|
@lazy_property
|
2018-06-01 12:21:32 +00:00
|
|
|
def _callbacks(self):
|
2018-07-16 09:17:06 +00:00
|
|
|
# pylint: disable=no-self-use
|
2018-06-01 12:21:32 +00:00
|
|
|
return []
|
2018-03-07 09:12:58 +00:00
|
|
|
|
|
|
|
def subscribe_callback(self, callback, *args, **kwargs):
|
2018-04-18 17:44:26 +00:00
|
|
|
"""
|
|
|
|
Subscribe a callable to invoke once an event is triggered.
|
|
|
|
:param callback: callable to be executed on events
|
2018-06-04 20:16:44 +00:00
|
|
|
:param args: arguments passed to callable
|
|
|
|
:param kwargs: kwargs passed to callable
|
2018-04-18 17:44:26 +00:00
|
|
|
"""
|
2018-03-07 09:12:58 +00:00
|
|
|
fun = partial(callback, *args, **kwargs)
|
|
|
|
self._callbacks.append(fun)
|
|
|
|
|
2018-06-28 15:31:55 +00:00
|
|
|
def subscribe_callbacks(self, *callbacks):
|
|
|
|
"""
|
|
|
|
Subscribe a list of callbacks to incoke once an event is triggered.
|
|
|
|
:param callbacks: callbacks to be subscribed
|
|
|
|
"""
|
|
|
|
for callback in callbacks:
|
|
|
|
self.subscribe_callback(callback)
|
|
|
|
|
2018-03-07 09:12:58 +00:00
|
|
|
def unsubscribe_callback(self, callback):
|
|
|
|
self._callbacks.remove(callback)
|
|
|
|
|
|
|
|
def _execute_callbacks(self, *args, **kwargs):
|
|
|
|
for callback in self._callbacks:
|
|
|
|
callback(*args, **kwargs)
|