18

I am looking for a way to automate showing and hiding a 'loading' message when calling an async service, so instead of doing this:

showLoadingWidget();

service.getShapes(dbName, new AsyncCallback() {
  public void onSuccess(Shape[] result) {
    hideLoadingWidget();
    // more here...
  }

  public void onFailure(Throwable caught) {
    hideLoadingWidget();
  //more here
  }
});

I'd like to do just this, but still show and hide the message at completion.

// this should be gone: showLoadingWidget();
service.getShapes(dbName, new AsyncCallback() {
    public void onSuccess(Shape[] result) {
        // this should be gone: hideLoadingWidget();
        // more here...
    }
    public void onFailure(Throwable caught) {
        //this should be gone:  hideLoadingWidget();
        //more here
    }
});

In short I would like to change the behavior of the async calls. Thank you for all the possible suggestions.

Daniel

1

6 Answers 6

19

You could wrap the call itself in an object that handles displaying the loading message, maybe retrying a few times on errors or whatever. Something like this:

public abstract class AsyncCall<T> implements AsyncCallback<T> {

    /** Call the service method using cb as the callback. */
    protected abstract void callService(AsyncCallback<T> cb);

    public void go(int retryCount) {
        showLoadingMessage();
        execute(retryCount);
    }

    private void execute(final int retriesLeft) {
        callService(new AsyncCallback<T>() {
            public void onFailure(Throwable t) {
                GWT.log(t.toString(), t);
                if (retriesLeft <= 0) {
                    hideLoadingMessage();
                    AsyncCall.this.onFailure(t);
                } else {
                    execute(retriesLeft - 1);
                }
            }
            public void onSuccess(T result) {
                hideLoadingMessage();
                AsyncCall.this.onSuccess(result);
            }
        });
    }

    public void onFailure(Throwable t) {
        // standard error handling
    }
    ...
}

To make the call do something like this:

new AsyncCall<DTO>() {
    protected void callService(AsyncCallback<DTO> cb) {
        DemoService.App.get().someService("bla", cb);
    }
    public void onSuccess(DTO result) {
        // do something with result
    }
}.go(3); // 3 retries

You could extend this with code to detect calls that are taking a long time and display a busy indicator of some kind etc.

1
4

The following AsyncCall is what I'm currently using (inspired by David Tinker's solution). Instead of retrying, this expects some RPC calls to take long time to return and displays a loading indicator if the call haven't returned before a specified timeout.

This AsyncCall also keeps track of the number of RPC calls currently in progress, and only hides the loading indicator if all RPC calls have returned. With David's solution, the loading indicator might be hidden by an earlier RPC call returning even though another is still in progress. This if course assumes the loading indicator widget is global for the app, which it is in my case.

public abstract class AsyncCall<T> {
    private static final int LOADING_TOLERANCE_MS = 100;

    private static int loadingIndicatorCount = 0;

    private Timer timer;
    private boolean incremented;
    private boolean displayFailure;

    public AsyncCall(boolean displayFailure) {
        this.displayFailure = displayFailure;

        timer = new Timer() {
            @Override
            public void run() {
                if (loadingIndicator++ == 0)
                    // show global loading widget here
                incremented = true;
            }
        };
        timer.schedule(LOADING_TOLERANCE_MS);

        call(new AsyncCallback<T>() {
            @Override
            public void onSuccess(T result) {
                timer.cancel();
                if (incremented && --loadingIndicatorCount == 0)
                    // hide global loading widget here
                callback(result);
            }

            @Override
            public void onFailure(Throwable caught) {
                timer.cancel();
                if (incremented && --loadingIndicatorCount == 0)
                    // hide global loading widget here
                if (AsyncCall.this.displayFailure)
                    // show error to user here
            }
        });

    protected abstract void call(AsyncCallback<T> cb);

    protected void callback(T result) {
        // might just be a void result or a result we 
        // wish to ignore, so do not force implementation
        // by declaring as abstract
    }
}
3

Full example (Robert)

public abstract class AsyncCall<T> implements AsyncCallback<T> 
{
    public AsyncCall()
    {
        loadingMessage.show();
    }

    public final void onFailure(Throwable caught) 
    {    
        loadingMessage.hide();    
        onCustomFailure(caught); 
    } 

    public final void onSuccess(T result) 
    {       
        hideLoadingMessage();       
        onCustomSuccess(result);     
    }
    /** the failure method needed to be overwritte */   
    protected abstract void onCustomFailure(Throwable caught);  
    /** overwritte to do something with result */
    protected abstract void onCustomSuccess(T result); 
}
1

You could create a default callback superclass which takes a LoadingMessage object argument in its constructor, and provides hook methods for subclasses, e.g. onSuccess0 and onFailure0.

The implementation would be similar to:

public final void onFailure(Throwable caught) {
    loadingMessage.hide();
    onFailure0(caught);
}

protected abstract void onFailure0(Throwable caught);
2
  • Thanks for your suggestion Robert. I am not that would work because GWT Async interface requires to have OnSucess() and OnFailure() functions implemented.
    – supercobra
    Aug 21, 2009 at 11:56
  • My code was just a skeleton. Implement in a similar manner onSuccess(T result) onSuccess0(T result). I don't see why this would not work. Aug 21, 2009 at 12:40
1

Here is my version, pretty much same as the above ones but with some differences

public abstract class LoadingAsyncCallback<T> implements AsyncCallback<T> {

    /**
     * Override this method and call the async service method providing the arguments needed.
     * @param args
     */
    public abstract void callService(Object... args);

    /**
     * Call execute() to actually run the code in overriden method callService()
     * @param args: arguments needed for callService() method
     */
    public void execute(Object... args) {
        //your code here to show the loading widget
        callService(args);
    }

    @Override
    public void onFailure(Throwable caught) {
        //your code here to hide the loading widget
        onCallbackFailure(caught);
    }

    @Override
    public void onSuccess(T result) {
        //your code here to hide the loading widget
        onCallbackSuccess(result);
    }

    public abstract void onCallbackFailure(Throwable caught);
    public abstract void onCallbackSuccess(T result);
}

A simple example could be the following:

MyServiceAsync myServiceAsync = GWT.create(MyService.class);

LoadingAsyncCallback loadingAsyncCallback = new LoadingAsyncCallback() {
    @Override
    public void callService(Object... args) {
        myServiceAsync.someMethod((String) args[0], (String) args[1], this);
    }

    @Override
    public void onCallbackFailure(Throwable caught) {

    }

    @Override
    public void onCallbackSuccess(Object result) {

    }
};

String name = "foo";
String login = "bar";
loadingAsyncCallback.execute(name, login );
0

In case anyone is looking for a way to mark a screen element (widget / component) as busy during an RPC call I've implemented a small utility.

It disables the component and inserts a 'div' with a particular style. Naturally this can all be undone too.

At time of writing this was the style applied to the div:

@sprite .busySpinner {
    gwt-image: "spinnerGif";
    background-repeat: no-repeat;
    background-position: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10000; /* Something really high */
}

And the utility methods:

/**
 * Disables the given component and places spinner gif over top.
 */
public static void markBusy(final Component c) {
    c.disable();
    ensureNotBusy(c);
    // NOTE: Don't add style to the component as we don't want 'spinner' to be disabled.
    c.getElement().insertFirst("<div class='" + STYLE.busySpinner() + "'/>");
}

/**
 * Enables the given component and removes the spinner (if any).
 */
public static void clearBusy(Component c) {
    c.enable();
    if (!ensureNotBusy(c)) {
        GWT.log("No busy spinner to remove");
    }
}

private static boolean ensureNotBusy(Component c) {
    Element first = c.getElement().getFirstChildElement();
    if (first != null && first.removeClassName(STYLE.busySpinner())) {
        first.removeFromParent();
        return true;
    }
    return false;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.