views:

35

answers:

1

Consider that we've a class named Foo that fires "ready" event when it's ready.

from observer import SubjectSet

class Foo:
  def __init__(self):
    self.events = SubjectSet()
    self.events.create('ready')

  def do_sth(self):
    self.events.fire('ready')

As you see, do_sth method makes ready instances of the Foo class. But subclasses will want to add new tasks/conditions that have to be done before emit ready event.

To solve this problem, I've coded a set of new classes named TaskPool, Task, ObserverTask. They are being used by the Foo class like this:

from observer import SubjectSet
from taskpool import TaskPool, ObserverTask

class Foo:
  def __init__(self):
    self.events = SubjectSet()
    self.events.create('task1')
    self.events.create('task2')
    self.events.create('ready')

    task1 = ObserverTask( self.events.get('task1') )
    task1 = ObserverTask( self.events.get('task2') )

    self.tasks = TaskPool()
    self.tasks.append( task1, task2 )

    self.tasks.events.add_listener('success',self.events.subjects.ready.emit)

 def complete_task1(self):
   self.events.fire('task1')

 def complete_task2(self):
   self.events.fire('task2')

Now, it fires "ready" event when it's taskpool fires "success" event. As you expect, the classes which will extend Foo can define new tasks that have to be completed before fire the ready event. By the way, almost all of the tasks are asynchronous.

Do you think that it's a good solution to the problem? I've been looking for better solutions but I guess I don't know the right search phrase.

Thanks.

+1  A: 

I think you do not actually define very exactly what is the problem you try to solve. However, there's nothing wrong with the solution. It's clearly asynchronous and event-driven. But I think in general the solution should also arrow for error conditions, i.e. what happens if task1 or task2 fails due to any reason---they should be maybe allowed to also send a 'failed' event, and then this should be also propagated out of Foo with some logic---i.e. if task1 fails, will task2 still run to completion or will it be aborted; and if task1 succeeds and task2 fails, will the main object report 'success' or 'failed' out or what? Just things to consider.

antti.huima