我正在寻找一种在调用异步服务时自动显示和隐藏“正在加载”消息的方法,所以不要这样做:
showLoadingWidget();
service.getShapes(dbName, new AsyncCallback() {
public void onSuccess(Shape[] result) {
hideLoadingWidget();
// more here...
}
public void onFailure(Throwable caught) {
hideLoadingWidget();
//more here
}
});
我只想这样做,但仍会在完成时显示和隐藏消息。
// 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
}
});
简而言之,我想更改异步调用的行为。感谢您提出所有可能的建议。
丹尼尔
最佳答案
您可以将调用本身包装在一个处理显示加载消息的对象中,可能会在出现错误或其他情况时重试几次。像这样:
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
}
...
}
要调用,请执行以下操作:
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
您可以使用代码对其进行扩展,以检测花费很长时间的调用并显示某种繁忙指示符等。
关于java - 调用异步函数时自动显示 'loading' 指示符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1309436/