更新外部回调变量

Update variable outside callback

我正在为 Android 使用 Facebook SDK。我有一个请求,它从我得到响应的地方有一个回调。我必须执行请求的次数不定,具体取决于我从请求中获得的响应。我试图在回调函数之外使用全局变量并使用响应更新它,但它不起作用。这是我处理它的方法。

全局变量:

int dataLength = -1;

要持续执行请求:

while (dataLength == -1){
getComments("20");
}

问题是 dataLength 似乎永远不会更新,尽管它应该在第一次调用时更新

请求和回调函数:

public void getComments(String offset){
GraphRequest request = GraphRequest.newGraphPathRequest(AccessToken.getCurrentAccessToken(), "/me/inbox",
                new GraphRequest.Callback() {
                    @Override
                    public void onCompleted(GraphResponse graphResponse) {
                        dataLength = graphResponse.getJSONObject().getJSONArray("data").length;
                    }
                });
Bundle parameters = new Bundle();
parameters.putString("limit", "20");
parameters.putString("offset", offset);
request.setParameters(parameters);
request.executeAsync();
}

一个问题是您的 while 循环和异步回调 运行 在不同的线程中,因此如果没有某种同步,则无法保证 dataLength 的值写入一个线程将在另一个中阅读。 (参见 "Memory Consistency Errors" in the Java Tutorials。)

解决该问题的最简单方法是添加 volatile 关键字:

private volatile int dataLength = -1;

这确保每次读取 dataLength 都会检索最新写入的值。