async callback in GWT

The Asynchronous Interface

The asynchronous interface is the one that your client-side code will use. Your code will call the service but not wait for a reply (hence the ‘asynchronous’ of course). The reply will go somewhere else.

That ‘somewhere else’ is a method in the client-side code and you have to tell the gizmo that does all the hard work where this method is. Since the calling code is not going to deal with the callback, the return type of the calling must be void. In order for the system to know where to send the result of the call, the calling code passes it the routine.

So, in clientCallsTheServer you call methodOnTheServer passing it (in our case) a string and a callbackMethod and then it goes on its way without waiting for an answer.

Some time later, the callbackMethod is run with the result of the call. Here’s our asynchronous interface. It MUST have the same name as the synchronous (server-side) interface, but with ‘Async’ tagged on the end. It must also be in the same place as the synchronous interface, i.e. somewhere inside the ‘client’ bit of your project.

public class RPCDemo extends Composite
{
    VerticalPanel panel = new VerticalPanel();

    public RPCDemo()
    {
        initWidget(panel);
        panel.setHorizontalAlignment(HasAlignment.ALIGN_CENTER);
        panel.setWidth("100%");
        Button button = new Button("Test RPC", new ClickListener()
        {
            public void onClick(Widget sender)
            {
                while (panel.getWidgetCount() > 1)
                    panel.remove(1);
                RPCService rpc = new RPCService();
                rpc.testRPC("Hello", callback);
            }
        });
        panel.add(button);
        panel.setCellWidth(button, "100%");
    }
    AsyncCallback callback = new AsyncCallback()
    {
        public void onFailure(Throwable caught)
        {
            panel.add(new HTML("Failed:" + caught.getMessage()));
        }

        public void onSuccess(Object result)
        {
            while (panel.getWidgetCount() > 1)
                panel.remove(1);
            panel.add(new HTML((String) result));
        }
    };
}

From Here
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s