Usage instructions
This module has a complete Observer/Observable implementation. To take advantage of this module, all you have to do is:
- Make your Observable classes inherit from
Observable(don’t forget to callObservable.__init__(self)in the constructor) - Make your Observer classes inherit from
Observer(don’t forget to callObserver.__init__(self)in the constructor) - At runtime, for each object you want to observe, call
self.observe(observable_object)in a method of your Observer object. - In your Observable object, every time an event happens, call:
...
self.broadcastEvent("MyEventName",argument1,argument2...)
...
- In your Observer object, implement a method named:
def processEvent(self,notifierObject,eventName,*args):
processEvent will receive the notifier object, an event name, and a variable number of arguments, every time broadcastEvent is called in any of the Observable objects that have been observe‘d()
That’s it. Keep in mind that processEvent() will be invoked in the same thread context as the code which called broadcastEvent() in the Observable object. Thus, processEvent() methods should return quickly and never do blocking operations (suggested technique for coping with blocking operations: run them in a separate thread, which sleeps until a flag is raised, and raise the flag in the processEvent() method as appropriate).
Cute example:
from Observable import Observable,Observed
class Cat(Observable): def init(self): Observable.init(self) ... def doMyLife(self): street = self.searchForFood() self.broadcastEvent("inNeighborhood",street) ...
class Dog(Observer): def init(self,neighborsCat): Observer.init(self) self.hatedCat = neighborsCat self.myStreet = "Fake Street" self.observe(neighborsCat) ... def processEvent(self,notifierObject,eventName,*arguments): if notifierObject == self.hatedCat: # the cat I was observing if eventName == "inNeighborhood": # the event name if arguments[0] == self.myStreet: # my street self.chaseCat(self.hatedCat) # chaseCat should return quickly