+
+class Service(Resource):
+ "Service that is activated only when someone is listening"
+ def __init__(self):
+ """
+ Initialise a service that can emit signals for the given event types
+ """
+ super(Service, self).__init__(types = [])
+ self.callbacks = dict()
+ for t in types:
+ self.callbacks[t] = set()
+
+ def shutdown(self):
+ self.stop()
+
+ def start(self):
+ "Activate the service"
+ pass
+
+ def stop(self):
+ "Deactivate the service"
+ pass
+
+ def notify(self, type, *args, **kw):
+ "Call all callbacks with the given parameters"
+ for cb in self.callbacks[type]:
+ cb(*args, **kw)
+
+ def has_callbacks(self):
+ for i in self.callbacks.values():
+ if i: return True
+ return False
+
+ def connect(self, type, callback):
+ "Connect a callback to this resource, activating it if needed"
+ do_start = not self.has_callbacks()
+ self.callbacks[type].add(callback)
+ if do_start:
+ self.start()
+
+ def disconnect(self, type, callback):
+ "Disconnect a callback to this resource, activating it if needed"
+ if not self.has_callbacks(): return
+ self.callbacks.discard(callback)
+ if not self.has_callbacks():
+ self.stop()