且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用异步函数时自动“加载”指示器

更新时间:2023-12-05 18:42:16

您可以将调用本身包装在处理显示加载消息的对象中,可能会在错误或其他方面重试几次。像这样:

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.