Tuesday, January 22, 2008

GWT - UIServiceAsync timing

I've been working a lot with GWT (google web toolkit), and have been using the user interface 'client side' , tying in to the back end. (server side). This introduces a few problems, especially with database calls. GWT translates Java into Javascript for you, but it doesn't try to generate javascript for the code you keep hidden away on the server side (thank goodness, especially since GWT currently only supports Java 1.4!)
So how does it know when the calls to the server side are complete?


Using AsyncCallbacks. These have onSuccess and onFailure methods you write yourself, which tell your UI side what to do when your server side calls have finished.


I have found that the timing of these prove to be a pain. Your client side code, like the tide and time, waits for no man. It will merrily march on, after you have made a call to get some data from the database for instance, and not care whether or not it has completed to run the next line. So you can't really depend on the feedback from the server side on the next line, your data might very well be null.
..or the line after that. or the next one.

So how do you make sure that darn query's output can be properly shown to the user?


the answer lies in the onSuccess method.
You make a structure to contain whatever you need on the UI side, and draw itself (as empty for now, or with a 'loading, please wait' message) to the screen.
Then, pass that container to the Async call. In the onSuccess method, you tell it to write the output to that container and draw itself again.


This way the user will always see something, and you won't get null Pointer exceptions.

2 comments:

Weav said...

This kind of thing shows up all kinds of places now. Async-IO packages of various sorts exist, and allow for event-driven coding of servers and stuff (look at "SEDA" - Scalable Event Driven Architecture" which can handle 10,000 clients on just a few threads).

Also AJAX uses this kind of thing in Javascript.

What's a little scary is you can get funny race conditions when the page isn't quite done displaying due to some other process getting to run, and your async callback goes before the container it's supposed to fill is done (if the page is written that way)...

--bakachichi

Kyra said...

Oh yes. I'm learning the hard way all about strange race conditions! We're embedding flash on some of our pages, and while it has nothing to do with our backend code, flash is finicky in certain versions of IE if the page is build in the wrong order. This requires either giving it a 'sleep' time, to hope the other async calls return first. There are probably more elegant ways to solve the flash problem...