Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

java - Is there a way to reuse builder code for retrofit

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Both the RestAdapter and the generated instance of your services (MyTaskService in this case) are extremely expensive objects and should be used as singletons.

This means that you should only ever call restAdapter.create once and re-use the same instance of MyTaskService every time you need to interact with.

I cannot stress this enough.

You can use the regular singleton pattern in order to ensure that there only is ever a single instance of these objects that you use everywhere. A dependency injection framework would also be something that could be used to manage these instances but would be a bit overkill if you are not already utilizing it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...