重用Retrofit方法

时间:2017-03-07 02:26:10

标签: android android-activity retrofit retrofit2

我有一个使用Retrofit调用我的服务器的方法:

public class MainActivity extends AppCompatActivity {

    // ... activity methods here, removed for simplicity ...

    // Used to subscribe to a user given their userId
    public void subscribeToUser(int userId) {
        final ApiInterface apiService = ApiClient.createService(ApiInterface.class);

        Call<BasicResponse> call = apiService.subscribe(userId);
        call.enqueue(new Callback<BasicResponse>() {
            @Override
            public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<BasicResponse> call, Throwable t) {
                Log.e(TAG, t.toString());
            }
        });
    }

}

我现在需要在另一个活动中使用相同的方法(subscribeToUser()),但将方法复制并粘贴到其他活动中是没有意义的。然后我会两次使用相同的代码。

那么我可以将方法放在一个地方让活动知道呼叫是成功还是失败?我应该如何组织这个?

这是我的ApiClient.java课程:

public class ApiClient {

    public static final String API_BASE_URL = "http://www.website.com/api/";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();

        return retrofit.create(serviceClass);
    }

    public static <S> S createService(Class<S> serviceClass, final String authToken) {
        if (authToken != null) {
            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Request original = chain.request();

                    // Request customization: add request headers
                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Authorization", "Bearer " + authToken)
                            .method(original.method(), original.body());

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });
        }

        OkHttpClient client = httpClient.build();
        Retrofit retrofit = builder.client(client).build();

        return retrofit.create(serviceClass);
    }
}

这是我的ApiInterface.java课程:

public interface ApiInterface {
    @FormUrlEncoded
    @POST("subscribe")
    Call<BasicResponse> subscribe(@Field("userId") Integer userId);
}

感谢。

1 个答案:

答案 0 :(得分:2)

在我看来,createService(ApiInterface.class)不应该被多次调用。它没有必要,也会降低您的应用程序速度。您可以尝试使用单例模式创建UserService,如下所示:

public class UserService {

private UserService userService;
final ApiInterface apiService;
//Contructor private to prevent init object from outside directly.
private UserService() {
    apiService = ApiClient.createService(ApiInterface.class);
}
//use this method when you need to use UserService 
public static UserService getInstance() {
    if(userService ==  null) {
        userService = new UserService();
    }
}

// Used to subscribe to a user given their userId
public void subscribeToUser(int userId, ServiceCallBack serviceCallBack) {
    final ApiInterface apiService = ApiClient.createService(ApiInterface.class);

    Call<BasicResponse> call = apiService.subscribe(userId);
    call.enqueue(new Callback<BasicResponse>() {
        @Override
        public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
            if (response.isSuccessful()) {
                Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show();
                serviceCallBack.successful(response);
            } else {
                Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call<BasicResponse> call, Throwable t) {
            Log.e(TAG, t.toString());
            serviceCallBack.fail(t);
        }
    });
}
//this is callback interface, help you know whether success from outside.
interface ServiceCallBack {
     void successful(Response response);
    void fail(Throwable t);
}
}

使用方法:

 UserService.getInstance(1, new ServiceCallBack(){

        @Override
        public void successful(Response response) {
            //process successful
        }

        @Override
        public void fail(Throwable t) {
            //process fail
        }
    });

现在,您可以将与User API相关的所有方法与UserService类相关联。