Retrofit完美封装

Retrofit最佳实现

话不多说,直接上代码

1.Rretrofit 封装
public class ServiceGenerator {
    //服务器地址
    private static final String BASE_URL = "";

    //retrofit builder
    private static Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create());

    //retrofit object
    private static Retrofit retrofit = builder.build();

    //log interceptor 打印网络请求日志
    private static HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);

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


    //service generator 供外部调用
    public static <S> S createService(Class<S> serviceClass){
        //未添加拦截器 且 处于开发模式
        if (!httpClientBuilder.interceptors().contains(loggingInterceptor) && BuildConfig.DEBUG)
        {
            httpClientBuilder.addInterceptor(loggingInterceptor);
            builder = builder.client(httpClientBuilder.build());
            retrofit = builder.build();
        }
        return retrofit.create(serviceClass);
    }
}
2.具体调用
RequestService service = ServiceGenerator.createService(RequestService.class);
service.listDevices().enqueue(new Callback<BaseResponse<List<Device>>>() {
    @Override
    public void onResponse(Call<BaseResponse<List<Device>>> call, Response<BaseResponse<List<Device>>> response) {

    }

    @Override
    public void onFailure(Call<BaseResponse<List<Device>>> call, Throwable t) {

    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Retrofit与协程的结合,可以通过封装来简化使用和处理异步操作。以下是一个简单的示例: 首先,你可以创建一个协程适配器(CoroutineCallAdapterFactory)并添加到Retrofit的Builder中: ```kotlin val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() ``` 接下来,你可以定义一个封装了异步操作的协程函数,例如: ```kotlin suspend fun <T> Call<T>.await(): T { return suspendCancellableCoroutine { continuation -> enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { if (response.isSuccessful) { response.body()?.let { continuation.resume(it) } ?: continuation.resumeWithException(NullPointerException("Response body is null")) } else { continuation.resumeWithException(HttpException(response)) } } override fun onFailure(call: Call<T>, t: Throwable) { if (continuation.isCancelled) return continuation.resumeWithException(t) } }) continuation.invokeOnCancellation { try { cancel() } catch (ex: Throwable) { // Ignore cancel exception } } } } ``` 这个函数将一个Retrofit的Call对象转换为一个挂起函数,它会在请求完成时返回结果或抛出异常。 最后,你可以在协程中使用封装后的Retrofit方法,例如: ```kotlin suspend fun fetchData(): List<Item> { val service = retrofit.create(ApiService::class.java) val response = service.getItems().await() return response.items } ``` 这样,你就可以使用协程的方式来发起异步请求并获取结果了。注意,上述代码中的`ApiService`是你自己定义的Retrofit接口。 希望以上示例能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值