调用异步函数时自动“加载”指示器 [英] Automatic 'loading' indicator when calling an async function
问题描述
我正在寻找一种在调用异步服务时自动显示和隐藏加载消息的方法,而不是这样做:
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
}
});
我想这样做,但仍然会在完成时显示和隐藏消息。 p>
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.
丹尼尔
推荐答案
您可以将调用本身包装在处理显示加载消息的对象中,可能会在错误或其他方面重试几次。像这样:
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.
这篇关于调用异步函数时自动“加载”指示器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!