Is there a way to reuse builder code for retrofit
android, java, retrofit
Solution
first you declare your parent class with all common behavior
public abstract class MyAbstractTask extends AsyncTask<String, String, String> {
protected void someMethod() { //note that i change private to protected
final RestAdapter restAdapter = new RestAdapter.Builder().setServer("http://10.0.2.2:8080").build();
final MyTaskService apiManager = restAdapter.create(MyTaskService.class);
}
}
then, you extend it with every task
public class MyTask extends MyAbstractTask {
//your someMethod() is available from everywhere in your class
}
public class MyOtherTask extends MyAbstractTask {
//your someMethod() is available from everywhere in your class
}
but i dont know where you are using restAdapter and apiManager, and if the actually need to be created once per task, since probably you can create it outside of these tasks.
If you create them outside, and then you need to use something inside your task, it is also good to have in mind the Dependency_injection pattern.
Also, you should avoid hardcoding values in your classes, like `http://10.0.2.2:8080`
You should use at least a `final static final String server= "http://10.0.2.2:8080"` and then use that, or better, use a setter or the constructor in the most inner class, and set tha values from the activity or the main controller.
Problem
I am using Retrofit and in every task I have to do something like this: ``` public class MyTask extends AsyncTask<String, String, String> { private void someMethod() { final RestAdapter restAdapter = new RestAdapter.Builder() .setServer("http://10.0.2.2:8080") .build(); final MyTaskService apiManager = restAdapter.create(MyTaskService.class); } // ... } ``` What is a good way to make this code DRY?