Improving the GWT Async Callback
The core of GWT framework for async communication to the server is through the async callback interface. Its interface is rather simple, but unfortunately, as with a lot GWT development the simplicity is lost with the the amount of boiler plate code you are constantly writing. You have to write a service interface, an async service interface, service implementation, and a class (or anonymous class) that extends the AsyncCallback. Also, if you have any framework code you want to add to your async calls, that is just more boiler plate code you need to add and make sure that everyone follows/uses when writing the client side calls to the async callback.
Needless to say, in my 1.5 years of writing GWT applications, I’m sick and tired of boiler plate code. I know boiler plate code is a result of issues with the Java language, but it seems like with GWT it is even more than with other projects. If only Google was working on a Groovy to Javascript GWT Compiler. But, since I’m confined to using Java, I will look into one area to reduce boiler plate code, and that is with the asynchronous service calls.
What is the GWT Asynchronous Service Interface?
The Asynchronous Service Interface is nice and simple. GWT, as with other client side libraries, have hidden the complexity of writing your AJAX calls. It is done by extending, usually through an anonymous inner class, the AsyncCallback interface.
The interface is just this:
public interface AsyncCallback<T> {
void onFailure(Throwable caught);
void onSuccess(T result);
}
You then have two service interfaces the standard interface, and the async interface
Standard Service Interface
@RemoteServiceRelativePath("gwt/MyService")
public interface MyService {
MyData getData(String parameter);
}
Async Service Interface
the return parameter is wrapped as a parameter in the AsyncCallback interface (shown above).
public interface MyServiceAsync {
void getData(String parameter, AsyncCallback<MyData> callback);
}
Calling the Service from GWT
public class MyClass {
@Inject
private MyServiceAsync service;
public void someMethod() {
service.getData(new AsyncCallback<MyData>() {
void onSuccess(MyData data) {
//success code goes here.
}
void onFailure(Throwable throwable) {
// failure code goes here.
}
});
}
}
The boiler-plate code
There is code that I end up writing around calling all of my AJAX services. I would like to add this code w/out having boiler-plate code all around my application.
- I want to log each call including the time needed to make the call
- I want certain exceptions to be handled in a uniform way across all of my calls
- I want the ability to retry the asynchronous service call.
If we look at the logging, adding code an existing Async Callback is easy enough. However, when you have many anonymous classes and more complex logging; it all adds up.
public class MyClass {
@Inject
private MyServiceAsync service;
public void someMethod() {
long start = System.currentTimeMillis();
service.getData(new AsyncCallback<MyData>() {
void onSuccess(MyData data) {
Log.debug("time : " + (System.currentTimeMillis() - start);
//success code goes here.
}
void onFailure(Throwable throwable) {
Log.debug("time (failure) : " + (System.currentTimeMillis() - start);
// failure code goes here.
}
});
}
}
Now, every time I make a service call, I need to add this boilerplate code.
The GwtCallbackWrapper
The solution is to wrap the AsyncCallback in another class, and use that class to make your async calls. Extending the AsyncCallback interface doesn’t work, since you cannot wrap the method calls and you end up providing alternate methods, but it is an interface (everythings public) so extending it just makes things more confusing. Instead, create a wrapper class that has the same methods, but creates a simple AsyncCallback that ends up calling the methods on the wrapped class. Then add a new onCall(AsyncCallback
Here is the AsyncCallback replacing that wraps that actual AsyncCallback. Since this is an abstract class, you can limit the scope of onSuccess(), onFailure(), and the newly added method onCall() to be protected. When used as an anonymous inner class, the onCall() method will have access to local variables (as long as they are final) as well as any class variables.
import com.google.gwt.user.client.rpc.AsyncCallback;
public abstract class GwtCallbackWrapper<T> {
private AsyncCallback<T> asyncCallback = new AsyncCallback<T>() {
public void onSuccess(T result) {
GwtCallbackWrapper.this.onSuccess(result);
}
public void onFailure(Throwable t) {
GwtCallbackWrapper.this.onFailure(t);
}
};
protected final AsyncCallback<T> getAsyncCallback() {
return asyncCallback;
}
protected abstract void onSuccess(T t);
protected abstract void onFailure(Throwable throwable);
protected abstract void onCall(AsyncCallback<T> callback);
public final void call() {
onCall(getAsyncCallback());
}
}
Now, I can easily add in my aspect like behavior w/out really changing the API to the user (the onFailure() and onSuccess() method names and signatures remain unchanged).
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.client.rpc.AsyncCallback;
public abstract class GwtCallbackWrapper<T> {
private long start;
private AsyncCallback<T> asyncCallback = new AsyncCallback<T>() {
public void onSuccess(T result) {
Log.debug("Time : " + (System.currentTimeMillis() - start));
GwtCallbackWrapper.this.onSuccess(result);
}
public void onFailure(Throwable t) {
Log.debug("Time (failure) : " + (System.currentTimeMillis() - start));
GwtCallbackWrapper.this.onFailure(t);
}
};
protected final AsyncCallback<T> getAsyncCallback() {
return asyncCallback;
}
protected abstract void onSuccess(T t);
protected abstract void onFailure(Throwable throwable);
protected abstract void onCall(AsyncCallback<T> callback);
public final void call() {
start = System.currentTimeMillis();
onCall(getAsyncCallback());
}
}
When I need to make an asynchronous call, I just use my wrapper class, never using the AsyncCallback directly.
public class MyClass {
@Inject
private MyServiceAsync service;
public void someMethod(final String parameter) {
new GwtCallbackWrapper<MyData>() {
public void onCall(AsyncCallback<MyData> callback) {
service.call(parameter, callback);
}
void onSuccess(MyData data) {
//success code goes here.
}
void onFailure(Throwable throwable) {
// failure code goes here.
}
}).call();
}
}
Don’t forget you will need to make any parameter or local variable of someMethod() to be final.
Now it is easy to add in even more “aspects” to the asynchronous calls. Lets say if you get 500 error back, you want to give the user a retry dialog.
GwtCallbackWrapper
import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.StatusCodeException;
public abstract class GwtCallbackWrapper<T> {
private long start;
private AsyncCallback<T> asyncCallback = new AsyncCallback<T>() {
public void onSuccess(T result) {
Log.debug("Time : " + (System.currentTimeMillis() - start));
GwtCallbackWrapper.this.onSuccess(result);
}
public void onFailure(Throwable t) {
Log.debug("Time (failure) : " + (System.currentTimeMillis() - start));
if (t instanceof StatusCodeException) {
StatusCodeException e = (StatusCodeException) t;
if (e.getStatusCode() >= 500) {
new MyDialog<T>(GwtCallbackWrapper.this).center();
} else {
GwtCallbackWrapper.this.onFailure(t);
}
} else {
GwtCallbackWrapper.this.onFailure(t);
}
}
};
protected final AsyncCallback<T> getAsyncCallback() {
return asyncCallback;
}
protected abstract void onSuccess(T t);
protected abstract void onFailure(Throwable throwable);
protected abstract void onCall(AsyncCallback<T> callback);
public final void call() {
start = System.currentTimeMillis();
onCall(getAsyncCallback());
}
}
MyDialog
It can “retry” the service call, by just calling the wrapper.call() method.
public class MyDialog<T> extends DialogBox {
public MyDialog(final GwtCallbackWrapper<T> wrapper) {
setText("Server not available, retry?");
Button ok = new Button("OK");
ok.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
MyDialog.this.hide();
wrapper.call();
}
});
Button quit = new Button("Quit");
quit.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
MyDialog.this.hide();
}
});
HorizontalPanel panel = new HorizontalPanel();
panel.add(ok);
panel.add(quit);
setWidget(panel);
}
}
Summary
By wrapping the actual GWT AsyncCallback and using the wrapping class as your base class to your anonymous classes you create for your callbacks, you have any easy way to control the common code from your GWT client code, at least when it comes to making your service calls.
Thanks. I’ve been searching it for some time.
Neil, this is a great article. Working through this problem with the example is ideal. Re-jigging the way AsynCallback callbacks are used becomes pretty important with more complex applications. This helped me take a new approach.