Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for async http to end before continuing?

In GWT is there any way to wait for asynchronous call to complete? I need the response to continue (It's a login screen so succes means changing to the actual game and failure means staying in the login screen).
Here is the call:

private void execRequest(RequestBuilder builder)
{
    try
    {
        builder.sendRequest(null, new RequestCallback()
        {
            public void onError(Request request, Throwable exception)
            {
                s = exception.getMessage();
            }

            public void onResponseReceived(Request request,
                    Response response)
            {
                s = response.getText();
            }
        });
    } catch (RequestException e)
    {
        s = e.getMessage();
    }
}

And here is the calling method:`

public String check()
{
    s = null;
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, baseUrl
            + "check&user=" + user + "&password=" + password);
    execRequest(builder);
    return s;
}

I need the check method to return the response (or error) and not to return null.
I tried the brain-dead solution of writing:`

while (s == null);

To wait for the call to finish but that just crushed the page in development mode.
(chrome said page is unresponsive and suggested to kill it)

like image 517
Daniel Shaulov Avatar asked Jan 19 '23 19:01

Daniel Shaulov


2 Answers

Embrace asynchrony, don't fight it!

In other words: make your check method asynchronous too, passing a callback argument instead of returning a value; and pass a callback to execRequest (simply replace every assignment to s with a call to the callback). You don't necessarily need to fire an event on an application-wide event bus, as Jai suggested: it helps in decoupling, but that's not always what you need/want.

like image 159
Thomas Broyer Avatar answered Jan 29 '23 09:01

Thomas Broyer


You should not check for completion that way. The best design practice here is to fire a custom event when the login async call completes.. and when you receive the event (through the event bus) you do the remaining tasks.

read up on http://code.google.com/webtoolkit/articles/mvp-architecture.html#events

like image 30
Jai Avatar answered Jan 29 '23 11:01

Jai