如何创建Singleton OkHtpp类并处理以前的请求

时间:2017-09-26 15:25:58

标签: java android okhttp

我正在使用带有android的Google Autocomplete Places API,而我正在尝试做的是:

  1. 每次用户在EditText中键入一个char时,都需要发出一个新的请求以获得预测结果。
  2. 我需要取消之前的请求,因为我需要的唯一结果是用户输入的最终地址/位置。
  3. 如果位置长度小于3个字符,则使用一些逻辑来清理RecyclerView。
  4. 这就是为什么我需要一个单例实例,我试过这个:

    public class OkHttpSingleton extends OkHttpClient {
    private static  OkHttpClient client = new OkHttpClient();
    
    public static OkHttpClient getInstance() {
        return client;
    }
    
    public OkHttpSingleton() {}
    
    public void CloseConnections(){
        client.dispatcher().cancelAll();
    }
    public List<PlacePredictions> getPredictions(){
        //// TODO: 26/09/2017  do the request!
        return null;
    }
    

    }

    但是我不确定这是否是正确的方法,因为在doc中它表示dispatcher().cancelAll()方法取消了所有请求但是我知道这样做是错误的!我更关心的是如何创建单身,然后是其他人。

    主要活动:

    Address.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if(s.length() > 3){
                    _Address = Address.getText().toString();
                    new AsyncTask<Void, Void, String>() {
                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                        }
    
                        @Override
                        protected String doInBackground(Void... params) {
                            try { // request...
                        }else{Clear the RecyclerView!}
    

1 个答案:

答案 0 :(得分:3)

您可以使用这个特定客户端实现一个单独的帮助程序类,该类保留一个OkHttpClient并涵盖所有自定义功能:

public class OkHttpSingleton {

    private static OkHttpSingleton singletonInstance;

    // No need to be static; OkHttpSingleton is unique so is this.
    private OkHttpClient client;

    // Private so that this cannot be instantiated.
    private OkHttpSingleton() {
        client = new OkHttpClient.Builder()
            .retryOnConnectionFailure(true)
            .build();
    }

    public static OkHttpSingleton getInstance() {
        if (singletonInstance == null) {
            singletonInstance = new OkHttpSingleton();
        }
        return singletonInstance;
    }

    // In case you just need the unique OkHttpClient instance.
    public OkHttpClient getClient() {
        return client;
    }

    public void closeConnections() {
        client.dispatcher().cancelAll();
    }

    public List<PlacePredictions> getPredictions(){
        // TODO: 26/09/2017  do the request!
        return null;
    }
}

使用示例:

OkHttpSingleton localSingleton = OkHttpSingleton.getInstance();
...
localSingleton.closeConnections();
...
OkHttpClient localClient = localSingleton.getClient();
// or
OkHttpClient localClient = OkHttpSingleton.getInstance().getClient();