Flex Chronicles #16: How to Know When a Cairngorm Command is Complete

It seems every Flex or Flash application I build eventually needs to have a ton of data garnered from the server upfront. In Cairngorm, an application framework for Flex, you typically use Commands to get your data. They have the option of utilizing a Business Delegate to make the actual call in case any data-massaging to and/or from the server needs to take place.

The issue becomes, however, a good written command is dumb; it does just what its name implies such as “get the user data” which is named GetUserDataCommand. While Cairngorm does provide an abstract base command class for you to extend to allow commands to be chained, you still have no clue when they’ve completed, nor the success or failure of such completion. You cannot make them too smart, however, because they suddenly aren’t portable.

For example, we have an application that has about 4 states that are applicable on start up. Does the user need to register? Does the user need to update their register information? Is the user registered, do they have existing form information? If so, what is that data?

This is accomplished by passing in the necessarey information via the URL. Those variables are then handled in a FrontController fashion to determine the application’s state at startup. While this works well, getting the specific data in order doesn’t. Asking the server-side guy(s) to give us the data in a different function, or even all of it in one complicates things not just for them, but for us. Granted there are plenty of reasonable changes, but this isn’t one of them. So, we end up needing to get data in a specific order.

Now, I could create a specific command specifically for this purpose. Since you can tell when a Business Delegate is done, you can have 1 command call 3 Delegates, in order, to get the data you need.

…however, this is a gregarious abuse of the reusability of Commands , and while isolated, you are effectively duplicating logic, and duplication of anything in code is bad. Quoting from The Pragmatic Programmer, be DRY – Don’t Repeat Yourself.

The simplest approach is to have all Commands to support callbacks. Callback handlers were how components back in Flash MX were created to allow events to be dispatched. Built in classes such as XML had supported such things since Flash 5; XML.onLoad = thisFunction; which translates to “XML, when your onLoad is fired, please call this function and pass in whether or not you failed”. This eventually graduated to the EventDispatcher style of dispatching events with context about those events in an object, and is now built-in into ActionScript 3 & Flash Player 8.5 with actual Event classes to allow strict typing, both at compile time and runtime.

Now, Commands don’t need to dispatch events. They themsevles are stateless, much like the XML object is. The XML class loads XML, and hands it to you when it’s done. Commands are the same way; they get data and stick it in a globally accessible place when they are done. The difference here is you have no clue when they are done.

It is reasonable to pass in the callback functionality to an event in the event.data. Commands that need context can pull data off of the event object that is passed into their execute method. This same entry mechinism can be utilized by also passing in a callback. “When you are done, please call this function”.

In Flex 2, this will have to be more strict, but in 1.5 you can be loose and not call the callback if there is no callback to call. Therefore, your Commands aren’t forced to abide by this way of doing things. Only 3 Commands out of the 27 I’m dealing with actually utilize a callback.

The way I approached it was to create a responder class which holds a callback function, and the scope to call it in. This responder class instance is passed into the Command. The Command keeps a copy of it, and when he has completed whatever it is he does, he calls the callback function.

That way, those who are dispatching events, and thus running commands know when they are done if they need to.

It’s important to note that since Cairngorm actually creates 1 instance of all Commands at startup, a Command will actually keep a reference to this callback for the life of the application. Thus, it’s imperative that you clear a callback object if none is passed in to ensure that no old callback data is retained and thus called. ARP doesn’t do this because ARP’s Controller creates and executes Commands when they are called, and doesn’t keep a reference to them.

The ideal thing to do is to utilize an interface so that only some Commands can utilize this feature, and it’s explicit which ones do and which ones don’t, but you know how deadlines go…

The steps:
– create a SimpleResponder class
– import into whatever class is dispatching the events to run commands (since you run Commands in Cairngorm by broadcasting an event)
– create an instance of the SimpleResponder class, passing in your callback function and scope
– stick this an object with the name “callback_obj”
– pass that object as the 2nd parameter to broadcastEvent
– if there is a callback in the event.data in your command, set it to the Commands’ internal reference, otherwise, delete the commands internal reference
– when the Command is done, call the runCallback function on the callback object, and pass any information about success or failure as a parameter(s)

Here is some pseudo code of the SimpleResponder class:

class SimpleResponder
{
        // scope the method is invoked in
        public var scope:Object;
        // a function that will be called when a Command is done
        public var method:Function;
        
        // when creating an instance, pass in the scope and function
        function SimpleResponder(p_scope:Object, p_method:Function)
        {
                scope = p_scope;
                method = p_method;
        }
        
        // this function is called when a Command is done
        // arguments are optional, but encouraged
        public function runCallback():Void
        {
                method.apply(scope, arguments);
        }
        
        public function toString():String
        {
                return "[class SimpleResponder]";
        }
}

Here is how you create a SimpleResonder class instance from whatever class is broadcasting the event via Cairngorm’s EventBroadcaster:

var sr:SimpleResponder = new SimpleResponder(this, onUserInfoReturned);

Broadcast your event like you usually do, and add your object as the 2nd parameter with the field name of “callback_obj”. This will be placed on the Event’s data property, and you can then access it by name in the Command’s execute method:

EventBroadcaster.getInstance().broadcastEvent( Controller.GET_USER,
                                              {callback_obj: sr} );

In your Command class, define a property up top to hold a reference to the callback_obj:

private var callback_obj:SimpleResponder;

In your Command’s execute method, inspect the Event’s data property to see if it has a callback_obj, and if so, store a reference to it internally, otherwise, set it to null explicitly to ensure the Command doesn’t retain state from past calls (don’t have to do this in ARP):

if(event.data.callback_obj != null)
{
        callback_obj = event.data.callback_obj;
}
else
{
        callback_obj = null
}

Finally, when your Command is completed, typically in your onResult or onFault functions defined in your Command, call the runCallback function, and pass in either a true or false… or whatever you want:

callback_obj.runCallback(true);

Your controller class, or whatever class is issuing commands, can then have a function defined looking like this to know when a Command is completed:

public function onUserInfoReturned(bool:Boolean):Void
{
        // show success or failure
}

This is a great way of handling server state because now you know exactly where things failed. This allows more control over what is shown when a server call is being made. You can now show a Loading window for example, and remove it when a call is completed instead of the default wait cursor. Even better, if you have multiple calls, you can utilize a ViewStack in your Loading Window to showcase many states of the linear operation (or non-linear if 5 unrelated calls for example) to know exactly which one is done, and actually visually represent that.

That’s a lot better than, “Um… the call failed, it must be the server guy’s fault, let’s go to lunch!” Now you, and the user, can see visually where it failed and why.

The downside is, the pontential for a race condition exists because if the same Command is called more than once, the later callback will overwrite the first, thus ensuring the first call never returns it’s result to those that care to know about it. I’m sure this can be easily fixed; either by changing how Cairngorm’s FrontController works (creating Commands on the fly vs. creating all initially on app startup), or by associating an ID… tons of ways, I’m sure.

5 Replies to “Flex Chronicles #16: How to Know When a Cairngorm Command is Complete”

  1. ‘Um… the call failed, it must be the server guy’s fault, let’s go to lunch!’….never tired that one… Just out of interest do you know if long method names and variable names still increase the size of the final swf in AS3 or have they implemented some sort of a hash table lookup in the compiled AS to keep sizes down.

    Cam.

  2. I think the hash table look up for method names is no longer a speed problem; since it’s now actually truly compiled, and they are on the traits object vs. the prototype object, it’s fast as nuts now, even with inheritance.

    However, I think it’s still physical bytecode representing your string names, thus, you have no choice on filesize. To me, ‘getUserInformation’ is better than ‘getUsrInfo’ just to save filesize, but bandwidth considerations haven’t entered my work considerations for over 4 years, so I’m spoiled in that aspect!

  3. Couldn’t your Commands just dispatch events, and circumvent the race condition of callbacks? Some people here have started using the ModelLocator for such things, as it is a singleton accessed by most aspects of app. However, you could also use Application.application to dispatch global events, as well… I’d be interested to hear if you considered using events, and if so, why you didn’t use them?

  4. I love your example!

    I have found in my experience that it is better to create a manager/handler class and just dispatch a ‘call complete’ event through the onResult method. Although a Handler separates the code from core cairngorm framework, it’s more optimal and removeable because applications should be event driven.

  5. As an update, if you’re using ActionScript 3.0, I believe runCallback() method should look like this:

    public function runCallback(…arguments):void{
    method.apply(scope,arguments);
    }

    Void needs to be lowercase :void and …arguments is required to allow dynamic params.

Comments are closed.