O
O
orbit0702019-07-01 12:28:30
Android
orbit070, 2019-07-01 12:28:30

Question about Retrofit - why is it implemented like that?

Here is an example of a simple class for working with Retrofit:

public class NetworkService {
    private static NetworkService mInstance;
    private static final String BASE_URL = "https://jsonplaceholder.typicode.com";
    private Retrofit mRetrofit;
 
    private NetworkService() {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
 
    public static NetworkService getInstance() {
        if (mInstance == null) {
            mInstance = new NetworkService();
        }
        return mInstance;
    }
    
    public JSONPlaceHolderApi getJSONApi() {
        return mRetrofit.create(JSONPlaceHolderApi.class);
    }
}

My main question is, why call every time create(JSONPlaceHolderApi.class)in the method getJSONApi()? Why create(JSONPlaceHolderApi.class)is it not called once (for example, in the constructor), but each time it will be called when calling getJSONApi ()?
And the second question - if I create several interfaces (JSONPlaceHolderApi, JSONPlaceHolderApi2, JSONPlaceHolderApi3, etc.), then I need to work with them through the same Retrofit instance, similar to how it is implemented for the interface in the example JSONPlaceHolderApi?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question