Retrofit implementation best practice

时间:2015-10-29 11:08:51

标签: android retrofit

We are building an App using Retrofit, where we have a separate module to connect with our backend. Now the way it is currently designed, in the module we have a RestClient class having rest adapters and interfaces defined with the routes. For the sake of simplicity I am providing one sample rest endpoint.

// Rest adapter instance
    private static RestAdapter getRestAdapter() {

        if (!isDebuggable) {
            URL = URL_PROD;
        } else {
            URL = URL_UAT;
        }

        if (mRestAdapter != null) {
            return mRestAdapter;
        }
        return mRestAdapter = new RestAdapter.Builder()
                .setEndpoint(URL)
                .setRequestInterceptor(authHeader())
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .build();
    }


private interface IApiClient {

        @POST("/register")
        void register(@Body JsonObject dataObject, Callback<SignInResponse> signInResponseCallback);

}

and the corresponding clients are defined as follows :

public static void register(JsonObject jsonObject, final ErrorNetworkResponse<SignInResponse> listener) {
        getRestAdapter().create(IApiClient.class).register(jsonObject, new Callback<SignInResponse>() {
            @Override
            public void success(SignInResponse signInResponse, Response response) {

                if (listener != null) {
                    listener.onSuccess(signInResponse);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("RegisterAPI", error.toString());
                if (listener != null) {
                    listener.onError(error);
                }
            }
        });
    }

Now I know this pattern is not optimal because 1. We have to make a large number of rest api requests so repeating this much code for every instance is not desirable. 2. Since we are calling the client directly from the Activity it might be prone to Android rotate view issue. What I am looking for is to use Otto / EventBus as the bus system to provide the api calls. But even then, how to reduce so much boilerplate code for a single async request? What are the best practices? Thanks in advance!

0 个答案:

没有答案