views:

82

answers:

1

Let's say that I have a bunch of objects (thumbnails in a matrix for example) and I need to load some data files for all of those over the network (HTTP). So each thumbnail has the thumbnail image itself and an xml file for instance.

There's a number of things that can go wrong from IO errors to bad URLs to badly formatted XML and so on. The question is what is the best / most elegant / most robust way of organizing all of this. What I usually end up doing is having a load manager that tells the child objects to start loading and then monitors the loading. The child objects have listeners for IO errors and HTTP status events. When all children have loaded everything (with some possible failures) something is done (the thumbnails are shown or whatever).

I was thinking that there has to be a better way of doing this, something that would allow me to maybe use throw clauses when errors occur. Throwing something from the listener isn't going to do much good of course. So what to do. Have a local flag(s) in the child objects and abort if something fails or what?

I am using AS3 but the question should be pretty much the same for other languages, at least for object oriented ones.

Just to be clear I'm not looking for any program code, just general ideas on a design pattern. I also realise that because of the asynchronous load I'm tied in to event handling at least in the child objects.

+2  A: 

i use a "queue" package which is able to deal with all sorts of asyncronous operations. the nice thing is you can nest these operations (composite pattern) and create quite complex stuff easily. if events occur you can catch them either at the root as they "bubble up the queue tree) or directly where they originate, depending on the listeners you add.

interface Qable extends IEventDispatcher {
   function start()
   function stop()
}
interface Q extends Qable {
   function add(item:Qable):Q
   function remove(item:Qable):Q
   ...
}

var q1: Q = new Q
q1.add(new Qable(...))
q1.add(new Qable(...))

var q : Q = new Q
q.addEventListener(Event.COMPLETE, onComplete)
q.addEventListener(Event.ERROR, onError)
q.add(new Qable(...))
q.add(new Qable(...)).addEventListener(Event.Error, onItemXError)
q.add(m1)

q.start()
maxmc
I see. So that would allow me to shift most of the event handling logic to the top level manager of the queue. Adding states (waiting/loading/success/fail) to the queue objects would come in handy as well I presume. Very clever, thanks.
Matti
yes indeed. client code becomes very structured and simple. my implementation is available at http://code.google.com/p/splinklibrary/
maxmc