def subscribe(self, event, callback):
""" Subscribe a callback to an event
:arg event: String name of an event to subscribe to
:callback: The function to call when the event is published. This can
be any python callable.
Use :func:`functools.partial` to call the callback with any other
arguments.
.. note:: The callback is registered with the event each time this
method is called. The callback is called each time it has been
registered when the event is published. For example::
>>> import asyncio
>>> import pubmarine
>>> pubpen = pubmarine.PubPen(asyncio.get_event_loop)
>>> def message():
... print('message called')
>>> pubpen.subscribe('test', message)
>>> pubpen.subscribe('test', message)
>>> pubpen.publish('test')
message called
message called
If the caller wants the callback to only be called once, it is the
caller's responsibility to only subscribe the callback once.
"""
if self._event_list and event not in self._event_list:
raise EventNotFoundError('{} is not a registered event'
.format(event))
# Get an id for the subscription
sub_id = next(self._next_id)
self._subscriptions[sub_id] = event
try:
# Add a method
self._event_handlers[event][sub_id] = WeakMethod(callback)
except TypeError:
# Add a function
self._event_handlers[event][sub_id] = ref(callback)
return sub_id
评论列表
文章目录