Reputation: 715
I'm using Google Autocomplete Places API with android and what I'm trying to do is:
That's why I need a singleton instance, I tried this :
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;
}
}
But I'm not sure if it is the right way to do, because in the doc it says that the dispatcher().cancelAll()
method cancel all the requests But I know that way is wrong! I'm more concerned in how to create a singleton then the rest.
The Main Activity:
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!}
Upvotes: 3
Views: 4583
Reputation: 3050
You can implement a singleton helper class that keeps one OkHttpClient
and cover all of your custom functionalities using this one particular client:
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;
}
}
Example use:
OkHttpSingleton localSingleton = OkHttpSingleton.getInstance();
...
localSingleton.closeConnections();
...
OkHttpClient localClient = localSingleton.getClient();
// or
OkHttpClient localClient = OkHttpSingleton.getInstance().getClient();
Upvotes: 8