簡體   English   中英

如何創建Singleton OkHtpp類並處理以前的請求

[英]How to create Singleton OkHtpp Class and handle previous requests

我正在使用帶有android的Google Autocomplete Places API,我正在嘗試做的是:

  1. 每次用戶在EditText中鍵入一個char時,它都需要發出一個新請求來獲取預測結果。
  2. 我需要取消之前的請求,因為我需要的唯一結果是用戶輸入的最終地址/位置。
  3. 然后使用一些邏輯來清理RecyclerView,如果位置長度小於3個字符。

這就是為什么我需要一個單例實例,我試過這個:

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!}

您可以使用這個特定客戶端實現一個單獨的幫助程序類,該類保留一個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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM