Allow adding listeners atomically

This commit is contained in:
Kovid Goyal 2022-08-07 10:26:16 +05:30
parent 7735c23028
commit 87d51c1802
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 8 additions and 1 deletions

View File

@ -628,14 +628,17 @@ class Cache:
# Cache Layer API {{{
@write_api
def add_listener(self, event_callback_function):
def add_listener(self, event_callback_function, check_already_added=False):
'''
Register a callback function that will be called after certain actions are
taken on this database. The function must take three arguments:
(:class:`EventType`, library_id, event_type_specific_data)
'''
self.event_dispatcher.library_id = getattr(self, 'server_library_id', self.library_id)
if check_already_added and event_callback_function in self.event_dispatcher:
return False
self.event_dispatcher.add_listener(event_callback_function)
return True
@write_api
def remove_listener(self, event_callback_function):

View File

@ -70,6 +70,10 @@ class EventDispatcher(Thread):
with suppress(ValueError):
self.refs.remove(ref)
def __contains__(self, callback):
ref = weakref.ref(callback)
return ref in self.refs
def __call__(self, event_name, *args):
if self.activated:
self.queue.put((event_name, self.library_id, args))