如何设计这个异步回调

时间:2013-09-21 17:32:57

标签: java oop asynchronous

设计我的三个课程时遇到问题,其中包括:
UserManager - 使用sessionManager从服务器检索数据 SessionManger - 当请求之间的空闲时间超过允许的最大值时,使用WebRequest,自动登录用户处理Web服务器上的Web会话和请求 WebRequest - 将数据发布到网站并返回它的响应(这是异步类)

// Posts dat to web server and returns response using Interface
public class WebRequest extends AsyncTask<String, Integer, byte[]> {
    interface DoneInterface {
        void onSuccess(byte []data);
        void onError(Exception e, String message);
    };
  // Sets interface to be called when request from server is done
  public void onDone(DoneInterface callable)
  // Requests data from server
  public boolean PostUrl(String url);

  // ... other methods, variables
}

// Handles auto login of user 
public class SessionManager {
    private WebRequest webRequest = null;

    // Creates request on web server, "callback" is interface that should be called when 
    // WebRequest instance is done with downloading response    
    public void Request(String url, HashMap data, WebRequest.DoneInterface callback) {
    webRequest.onDone(new WebRequest.DoneInterface() {    
      @Override
      public void onSuccess(byte[] data) {
        // HERE I NEED TO DO SOME ACTION BEFORE CALLING callback.onSuccess 
        // that was passed as argument and will process data     

        callback.onSuccess(data);               
      }

      @Override
      public void onError(Exception e, String message) {
        // IF error, we will need to crate new session probalby
        sandManager = null;

        // Call callback (interface) passed as argument
        callback.onError(e, message);
      }
    });
    webRequest.PostUrl(url);
  }
  // ... other methods, variables
}

// Main class
class User {
  private SessionManager session = new SessionManager();

  public SomeMethod() {
    session.Request(new WebRequest.DoneInterface() {    
      @Override
      public void onSuccess(byte[] data) {
        // Here I need to process data received from web server                     
      }

      @Override
      public void onError(Exception e, String message) {}
    });
  }
}

我收到此错误 Cannot refer to a non-final variable "callback" inside an inner class defined in a different method(SessionManager, callback.onSuccess(data); 行)。我知道这是因为“回调”变量不是final。但是我应该如何设计这个类,以便在将它们传递给User之前我可以更改从SessionManager 中的WebRequest 返回的数据

1 个答案:

答案 0 :(得分:0)

即使您创建变量final,也可以这样做。 final仅表示您无法为本地变量分配新值。如果将局部变量放入内部类然后更改,则可以消除混淆。如果您不需要将callback重新命名为新回调,则final不会限制您。只要把它final,相信我,一切都会好的。