保存来自请求的响应变量 - GWT
Save response variable from Request - GWT
我需要保存来自请求的响应变量,areaRequest 是一个 RequestContext,它可以工作,但我无法保存它并在范围外使用它
Long temp;
areaRequest.countByCurrentInstitution().fire(new Receiver<Long>() {
@Override
public void onSuccess(Long response) {
temp = response;
}
});
您不能在 Receiver 内部使用外部 non-final 变量。
为了避免范围问题而进行的快速而肮脏的更改是:
final Long[] temp = {-1};
areaRequest.countByCurrentInstitution().fire(new Receiver<Long>() {
@Override
public void onSuccess(Long response) {
temp[0] = response;
}
});
doSomethingWith(temp[0]);
但这通常不是您想要做的。因为(如果)countByCurrentInstitution()
是一个异步调用,所以在您调用 doSomethingWith()
时 temp[0]
仍然是 -1
,因为异步方法仍然是 运行另一个线程。
您可以通过使用一个简单的 Thread.sleep()
或(哎呀!)一个很长的循环让您的主线程稍等片刻,但是,同样,这只是一个快速的 hack 并且容易出错(如果调用时间比这更长怎么办? ).
最好的选择是放弃 Long temp
并将您的代码移动到 onSuccess()
方法中:
areaRequest.countByCurrentInstitution().fire(new Receiver<Long>() {
@Override
public void onSuccess(Long response) {
doSomethingWith(response);
}
});
好吧,在使用 GWT 工作了很多时间之后,我找到的解决方案是创建嵌套的异步调用。
areaRequest.countByCurrentInstitution().fire(new Receiver<Long>() {
@Override
public void onSuccess(Long response) {
// Here I pass the value from the first request
anotherRequest.anotherFunction(response).fire(new Receiver<Long>(){
@Override
public void onSuccess(Long new_response){ // Long again it could be anything it depends of your function
doWhateverYouWant(new_response)
}
});
}
});
我需要保存来自请求的响应变量,areaRequest 是一个 RequestContext,它可以工作,但我无法保存它并在范围外使用它
Long temp;
areaRequest.countByCurrentInstitution().fire(new Receiver<Long>() {
@Override
public void onSuccess(Long response) {
temp = response;
}
});
您不能在 Receiver 内部使用外部 non-final 变量。
为了避免范围问题而进行的快速而肮脏的更改是:
final Long[] temp = {-1};
areaRequest.countByCurrentInstitution().fire(new Receiver<Long>() {
@Override
public void onSuccess(Long response) {
temp[0] = response;
}
});
doSomethingWith(temp[0]);
但这通常不是您想要做的。因为(如果)countByCurrentInstitution()
是一个异步调用,所以在您调用 doSomethingWith()
时 temp[0]
仍然是 -1
,因为异步方法仍然是 运行另一个线程。
您可以通过使用一个简单的 Thread.sleep()
或(哎呀!)一个很长的循环让您的主线程稍等片刻,但是,同样,这只是一个快速的 hack 并且容易出错(如果调用时间比这更长怎么办? ).
最好的选择是放弃 Long temp
并将您的代码移动到 onSuccess()
方法中:
areaRequest.countByCurrentInstitution().fire(new Receiver<Long>() {
@Override
public void onSuccess(Long response) {
doSomethingWith(response);
}
});
好吧,在使用 GWT 工作了很多时间之后,我找到的解决方案是创建嵌套的异步调用。
areaRequest.countByCurrentInstitution().fire(new Receiver<Long>() {
@Override
public void onSuccess(Long response) {
// Here I pass the value from the first request
anotherRequest.anotherFunction(response).fire(new Receiver<Long>(){
@Override
public void onSuccess(Long new_response){ // Long again it could be anything it depends of your function
doWhateverYouWant(new_response)
}
});
}
});