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

Nat*_*ros 2 java android okhttp

我正在将 Google Autocomplete Places API 与 android 一起使用,我想要做的是:

  1. 每次用户在 EditText 中键入一个字符时,它都需要发出一个新请求来获得预测结果。
  2. 我需要取消之前的请求,因为我需要的唯一结果是用户输入的最终地址/位置。
  3. 如果位置长度小于 3 个字符,然后使用一些逻辑来清理 RecyclerView。

这就是为什么我需要一个单例实例,我试过这个:

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;
}
Run Code Online (Sandbox Code Playgroud)

}

但我不确定这是否是正确的方法,因为在文档中它说该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!}
Run Code Online (Sandbox Code Playgroud)

Meh*_*med 6

您可以实现一个单例帮助程序类,该类保留一个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

使用示例:

OkHttpSingleton localSingleton = OkHttpSingleton.getInstance();
...
localSingleton.closeConnections();
...
OkHttpClient localClient = localSingleton.getClient();
// or
OkHttpClient localClient = OkHttpSingleton.getInstance().getClient();
Run Code Online (Sandbox Code Playgroud)